PHP Abstract Classes Explained: Usage Guide
In PHP, ‘abstract’ is a keyword used to declare an abstract class or method. An abstract class cannot be instantiated and can only be inherited, and it can contain abstract methods. Abstract methods are methods without specific implementations that need to be inherited and implemented by subclasses.
原文:我喜欢去海边散步。
Option: I enjoy taking a walk by the seaside.
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;
}
}
$circle = new Circle(5);
echo $circle->calculateArea(); // 输出: 78.54
In the example above, the Shape class is an abstract class that contains an abstract method calculateArea(). The Circle class inherits from the Shape class and implements the calculateArea() method to calculate the area of a circle.