An **Abstract Class** is a class that cannot be instantiated on its own. It serves as a blueprint for other classes. Abstract classes are used when you want to provide a common base for several child classes while ensuring they all implement certain methods.
An abstract class is defined using the abstract keyword. It can contain both regular methods (with code) and **Abstract Methods** (without code).
When a child class inherits from an abstract class, it **must** provide the implementation for all the abstract methods defined in the parent class.
An abstract method is a method that is declared in the parent class but has no body (no code). It simply defines the method signature (name and arguments).
<?php
abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name;
}
// Abstract method
abstract public function intro() : string;
}
?>
When you extend an abstract class, the child class must implement all abstract methods with the same (or less restricted) visibility.
<?php
abstract class Animal {
abstract protected function makeSound();
}
class Cat extends Animal {
public function makeSound() {
echo "Meow! ";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Bark! ";
}
}
$cat = new Cat();
$cat->makeSound();
$dog = new Dog();
$dog->makeSound();
?>
$myAnimal = new Animal(); would result in a Fatal Error.
When inheriting from an abstract class, there are three main rules the child class must follow:
protected, the child's can be protected or public, but not private).Database class).