What is Abstract Class in PHP: Definition and Usage
abstract class in PHP is a class that cannot be instantiated on its own and is meant to be extended by other classes. It can contain abstract methods, which are declared but not implemented, forcing child classes to provide their own implementations.How It Works
Think of an abstract class as a blueprint for other classes. It sets up a basic structure but leaves some parts unfinished, like a recipe that lists ingredients but not the cooking steps. You cannot create an object directly from an abstract class because it is incomplete by design.
In PHP, an abstract class can have both regular methods with code and abstract methods without code. The abstract methods act like promises that any class extending this abstract class must fulfill by providing their own specific code. This ensures a consistent interface while allowing flexibility in implementation.
Example
This example shows an abstract class Animal with an abstract method makeSound(). The child classes Dog and Cat implement this method differently.
<?php abstract class Animal { abstract public function makeSound(); public function sleep() { echo "Sleeping...\n"; } } class Dog extends Animal { public function makeSound() { echo "Bark!\n"; } } class Cat extends Animal { public function makeSound() { echo "Meow!\n"; } } $dog = new Dog(); $dog->makeSound(); // Outputs: Bark! $dog->sleep(); // Outputs: Sleeping... $cat = new Cat(); $cat->makeSound(); // Outputs: Meow! $cat->sleep(); // Outputs: Sleeping...
When to Use
Use abstract classes when you want to define a common template for a group of related classes but expect each to have its own specific behavior. For example, in a program managing different types of animals, an abstract class can define shared features like sleep() while requiring each animal to define its own makeSound().
This helps organize code, enforce rules, and avoid duplication by sharing common code in the abstract class while allowing customization in subclasses.
Key Points
- An abstract class cannot be instantiated directly.
- It can contain both abstract methods (without body) and concrete methods (with body).
- Child classes must implement all abstract methods.
- Abstract classes help enforce a consistent interface across related classes.
- They promote code reuse by sharing common functionality.