What is an Abstract Class in PHP?
An abstract class in PHP is a class that cannot be instantiated on its own and is designed to be inherited by other classes. It provides a way to define a blueprint for other classes to follow and can contain both abstract and concrete methods. Abstract classes are used in object-oriented programming to promote code reuse, modularity, and flexibility.
Definition and Purpose
An abstract class is defined using the abstract keyword in PHP. The purpose of an abstract class is to provide a partial implementation of a class, which can then be completed by subclasses. Abstract classes can contain state (properties) and behavior (methods), but they cannot be instantiated directly.
Key Characteristics
Abstract classes have the following key characteristics:
- Cannot be instantiated on their own
- Can contain both abstract and concrete methods
- Can have state (properties) and behavior (methods)
- Must be inherited by other classes to be used
Abstract Methods
Abstract methods are methods declared in an abstract class without an implementation. They must be implemented by any non-abstract subclass. Abstract methods are declared using the abstract keyword and have no function body.
Example of an Abstract Class in PHP
The following example demonstrates the use of an abstract class in PHP:
abstract class Shape {
abstract public function area();
public function display() {
echo "This is a shape.";
}
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * pow($this->radius, 2);
}
}
$circle = new Circle(5);
echo $circle->area();
echo $circle->display();
Benefits of Abstract Classes
Abstract classes provide several benefits, including:
- Code reuse: Abstract classes can provide a common implementation for multiple subclasses.
- Modularity: Abstract classes can help to break down a complex system into smaller, more manageable modules.
- Flexibility: Abstract classes can be used to create a variety of different classes that share a common base class.
1 thought on “What is an Abstract Class in PHP?”