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

PHP 函数的抽象和继承
抽象函数
抽象函数只声明函数签名,但没有提供实现。子类必须实现抽象函数,否则将出现错误。
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;
}
}实战案例
创建一个计算不同形状面积的程序:
立即学习“PHP免费学习笔记(深入)”;
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
声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!



