DEV Community

Cover image for Abstract Classes & Methods
AI_Dosage
AI_Dosage

Posted on

2 1

Abstract Classes & Methods

Abstract Classes & Methods

For Abstract Classes to exist there must be a parent class and a child class relationship. That means they can only exist in a situation a class inherits from another.

Abstract methods, in the child class have access to the both the public, protected and _construct properties.

Points to note:

  • you have to declare an abstract method or class using the abstract keyword -For abstract methods they must have the same name in the child class as in the parent class. They must have the same number of arguments, however a child method can have additional arguments.
  • The child class method must be defined with the same or a less restricted access modifier. Private wont work.

Let us look at the following example:

<?php  
abstract class Person{
 public $name;

 public function __construct($name){
  $this->name= $name;
 }
 abstract function greet();
}
class Greeting extends Person{
   public function greet() {
      echo "Hello, {$this->name}";
   }
}

$person1 = new Greeting("Samuel");
$person1->greet();
Enter fullscreen mode Exit fullscreen mode

Let us look at this other example where abstract method has argument:

<?php
abstract class Person{
 public $name;

 public function __construct($name){
  $this->name= $name;
 }
 abstract protected function greet($honor);
}
class Greeting extends Person{
   public function greet($honor) {
      echo "Hello, {$honor} {$this->name} ";
   }
}

$person1 = new Greeting("Samuel");
$person1->greet("Hon");
Enter fullscreen mode Exit fullscreen mode

Let us look at this other example where the child abstract method has optional argument:

<?php
abstract class Person{
 public $name;

 public function __construct($name){
  $this->name= $name;
 }
 abstract protected function greet($honor);
}
class Greeting extends Person{
   public function greet($honor,$salutation ="Welcome",$location ="Jamrock ") {
      echo "Hello, {$honor} {$this->name} {$salutation} to {$location} ";
   }
}

$person1 = new Greeting("Samuel");
$person1->greet("Professor");
Enter fullscreen mode Exit fullscreen mode

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series đź“ş

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series đź‘€

Watch the Youtube series