php 中抽象函数仅声明函数签名,由子类实现;继承允许子类继承父类属性和方法。通过抽象类 shape 和继承子类 rectangle 和 circle,可以创建不同形状并计算其面积,如示例中所示的矩形和圆形。

抽象函数只声明函数签名,但没有提供实现。子类必须实现抽象函数,否则将出现错误。
abstract class Shape {
abstract public function getArea();
} 继承PHP 支持类的继承,允许子类继承父类的属性和方法。
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
} 实战案例创建一个计算不同形状面积的程序:
abstract class Shape {
abstract public function getArea();
}
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function getArea() {
return pi() * $this->radius ** 2;
}
}
// 创建不同的形状对象
$rectangle = new Rectangle(5, 10);
$circle = new Circle(10);
// 计算并打印它们的面积
echo "矩形面积:{$rectangle->getArea()}\n";
echo "圆形面积:{$circle->getArea()}\n"; 输出:
矩形面积:50 圆形面积:314.1592653589793
以上就是PHP 函数的抽象和继承的详细内容,更多请关注知识资源分享宝库其它相关文章!







发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。