Abstract Classes & Methods

bazeng

Samuel K.M

Posted on October 28, 2021

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
💖 💪 🙅 🚩
bazeng
Samuel K.M

Posted on October 28, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related