What is Abstract Class in PHP?

An abstract class serves as a blueprint for other classes and cannot be instantiated directly. It may include both abstract methods (no body) and regular methods. Any class that extends an abstract class must implement all of its abstract methods. Abstract classes help enforce a structure and promote code consistency in OOP.

1. Basic Abstract Class Example


abstract class Animal {
    abstract public function makeSound(); // Abstract method

    public function eat() {
        return "Eating...";
    }
}

class Dog extends Animal {
    public function makeSound() {
        return "Woof!";
    }
}

$dog = new Dog();
echo $dog->makeSound(); // Output: Woof!
echo $dog->eat();       // Output: Eating...

File: abstract_class_example.php

2. Why Use Abstract Classes?

  • To provide a common structure for related classes.
  • To enforce method implementation in child classes.
  • Ideal when some behavior is shared, and some must be customized.

3. Key Rules of Abstract Classes

Rule Description
Cannot create object directly $obj = new AbstractClass(); ❌ Error
Can contain abstract and normal methods ✅ Yes
Child class must implement all abstract methods ✅ Required
Use abstract keyword for class/method abstract class, abstract function