An abstract class in PHP provides a blueprint for other classes. It defines common methods and forces child classes to implement required behavior.
Abstract classes are declared using the abstract keyword. Any method declared abstract must be implemented by child classes.
// Abstract class defining common behavior
abstract class Animal {
// Abstract method to be implemented by child classes
public abstract function makeSound();
// Concrete method shared by all animals
public function sleep() {
echo "Sleeping...";
}
}
// Dog class extending abstract Animal
class Dog extends Animal {
public function makeSound() {
echo "Bark!";
}
}
// Creating object of child class
$dog = new Dog();
$dog->makeSound();
$dog->sleep();
The Dog class implements the abstract method makeSound(). The object can call both abstract and concrete methods.
Think of an abstract class as a contract. Every child class must agree to implement required methods before it can be used.
Vehicle classstartEngine() abstract methodCar and Bike