Learn PHP Tutorial

PHP OOP – Abstract Classes


Abstract classes are the classes that has at least one abstract method. An abstract class can contain abstract methods as well as non abstract methods.

Let us understand by an example:

<?php
  
// Abstract class 
abstract class MainClass
{
    abstract public function method1();
    abstract public function method2($name, $color);
    abstract public function method3(): string;
}

?>

When a child class inherits from an abstract class, it must be defined with the same or less restricted access modifier. Suppose if the abstract method is defined as protected, the child class method must be defined as either protected or public. The type and number of arguments must be the same. However, the child class may have optional arguments in addition.

There are some basic rules to implement abstract class concept:

  • The child class method must be defined with the same abstract method name and redeclared the parent abstract method.
  • The child class method must have less restricted or at least same access modifier.
  • The number of arguments must be the same. However, the child class may have some optional arguments in addition.

Let us understand with an example

<?php
// Parent class
abstract class Car {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  abstract public function about() : string;
}

// Child classes
class Audi extends Car {
  public function about() : string {
    return "Choose German quality! I'm an $this->name!";
  }
}

class Volvo extends Car {
  public function about() : string {
    return "Proud to be Swedish! I'm a $this->name!";
  }
}

class Toyota extends Car {
  public function about() : string {
    return "Japan excellence! I'm a $this->name!";
  }
}

// Create objects from the child classes
$audi = new audi("Audi");
echo $audi->about();
echo "<br>";

$volvo = new volvo("Volvo");
echo $volvo->about();
echo "<br>";

$toyota= new toyota("Toyota");
echo $toyota->about();
?>

Here about() method is an abstract method defined in parent class. So, post inheriting redeclaration of about() method becomes mandatory. And hence defined in each class.