PHP OOP – Abstract Classes

In PHP OOP, an abstract class is a class that cannot be instantiated, but is instead meant to be extended by other classes. Abstract classes are used to define a common interface for a set of subclasses, and they can contain abstract methods that are not implemented in the abstract class, but must be implemented in the subclasses.

Here’s an example of an abstract class:

abstract class Animal {
    protected $name;
    
    public function __construct($name) {
        $this->name = $name;
    }
    
    abstract public function makeSound();
}
class Dog extends Animal {
    public function makeSound() {
        echo $this->name . " is barking.<br>";
    }
}
class Cat extends Animal {
    public function makeSound() {
        echo $this->name . " is meowing.<br>";
    }
}
//$animal = new Animal("Animal"); // Error: Cannot instantiate abstract class Animal.
$dog = new Dog("Dog");
$cat = new Cat("Cat");
$dog->makeSound(); // Output: Dog is barking.
$cat->makeSound(); // Output: Cat is meowing.

In this example, the Animal class is an abstract class that has a constructor that initializes the name property, and an abstract method named makeSound(). The Dog and Cat classes extend the Animal class and implement the makeSound() method.

We cannot create an object of the Animal class, because it is an abstract class:

//$animal = new Animal("Animal"); // Error: Cannot instantiate abstract class Animal.

We can create objects of the Dog and Cat classes, and call their makeSound() method:

$dog = new Dog("Dog");
$cat = new Cat("Cat");
$dog->makeSound(); // Output: Dog is barking.
$cat->makeSound(); // Output: Cat is meowing.

In summary, abstract classes in PHP OOP are classes that cannot be instantiated, but are meant to be extended by other classes. They are used to define a common interface for a set of subclasses, and can contain abstract methods that are not implemented in the abstract class, but must be implemented in the subclasses.