PHP Abstract Classes: Define & Use
In PHP, an abstract class is a class that cannot be instantiated and can only be used as a base class for other classes. It can contain both abstract and non-abstract methods, and is defined using the keyword ‘abstract’.
Here is an example of defining an abstract class:
abstract class Shape {
abstract public function calculateArea();
public function display() {
echo "This is a shape.";
}
}
In the example above, the Shape class is an abstract class that includes an abstract method calculateArea() and a non-abstract method display().
To work with an abstract class, you can create a concrete subclass by inheriting from the abstract class and implementing its abstract methods. Here is an example using the Shape abstract class:
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
}
$circle = new Circle(5);
echo $circle->calculateArea(); // 输出78.54
$circle->display(); // 输出This is a shape.
In the example above, the Circle class inherits from the Shape abstract class and implements the calculateArea() method. By creating an instance of the Circle class, we can call the calculateArea() method and display() method.
In general, abstract classes in PHP serve as templates for defining classes, allowing subclasses to inherit and implement their methods to promote code reusability and extension.