PHP - Extending Abstract Classes
Extending abstract classes in PHP is a way to create a more specific class that inherits the properties and methods of an abstract base class. The child class must provide implementations for all abstract methods defined in the abstract parent class. This allows you to build a hierarchy of classes with a shared structure and behavior while allowing customization in the child classes. Here's how to extend abstract classes in advanced PHP:
Defining an Abstract Base Class:
abstract class Shape {
abstract public function calculateArea();
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
}
In this example:
The Shape class is defined as an abstract class with an abstract method calculateArea().
The Circle class extends the abstract Shape class and provides a concrete implementation for the calculateArea() method.
Creating Another Subclass:
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function calculateArea() {
return $this->width * $this->height;
}
}
Here, the Rectangle class also extends the abstract Shape class and provides its own implementation for the calculateArea() method.
Using Extended Abstract Classes:
$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);
echo "Circle Area: " . $circle->calculateArea(); // Output: Circle Area: 78.539816339745
echo "Rectangle Area: " . $rectangle->calculateArea(); // Output: Rectangle Area: 24
In this example, you can treat both the Circle and Rectangle objects as instances of the Shape abstract class. The objects implement the required calculateArea() method, which demonstrates the concept of extending abstract classes and adhering to a common contract.
Key points about extending abstract classes:
A child class that extends an abstract class must provide implementations for all the abstract methods declared in the parent class.
Non-abstract methods in the abstract class can also be inherited and used by child classes.
Abstract classes are often used to define a general structure or behavior that needs to be shared by multiple related classes, while allowing customization in each class.
Extending abstract classes allows you to create a hierarchy of classes with varying levels of specificity while maintaining a shared structure and interface defined in the abstract parent class.