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

php 函数的抽象和继承
抽象函数
抽象函数只声明函数签名,但没有提供实现。子类必须实现抽象函数,否则将出现错误。
|
1
2
3
|
abstract class Shape {
abstract public function getArea();
}
|
继承
PHP 支持类的继承,允许子类继承父类的属性和方法。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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免费学习笔记(深入)”;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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";
|
输出:
|
1
2
|
矩形面积:50
圆形面积:314.1592653589793
|