多态是封装、继承之外的另一个面向对象基础特性。简单理解:不同对象实现相同接口或相同方法名,调用时可以表现出不同结果。
下面用形状接口、矩形类和圆形类说明。
示例代码
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| <?php
interface Shape { public function area();
public function perimeter(); }
class Rect implements Shape { private $width;
private $height;
public function __construct($width, $height) { $this->width = $width; $this->height = $height; }
public function area() { return '矩形的面积是:' . ($this->width * $this->height); }
public function perimeter() { return '矩形的周长是:' . (2 * ($this->width + $this->height)); } }
class Circular implements Shape { private $radius;
public function __construct($radius) { $this->radius = $radius; }
public function area() { return '圆形的面积是:' . (3.14 * $this->radius * $this->radius); }
public function perimeter() { return '圆形的周长是:' . (2 * 3.14 * $this->radius); } }
$shape = new Rect(5, 10); echo $shape->area() . '<br>'; echo $shape->perimeter() . '<br>';
$shape = new Circular(10); echo $shape->area() . '<br>'; echo $shape->perimeter() . '<br>';
|
输出结果
1 2 3 4
| 矩形的面积是:50 矩形的周长是:30 圆形的面积是:314 圆形的周长是:62.8
|
理解重点
Rect 和 Circular 都实现了 Shape 接口,所以它们都需要提供 area() 和 perimeter() 方法。
同一个变量 $shape,第一次指向矩形对象,第二次指向圆形对象。调用同名方法时,不同对象给出了不同结果,这就是一种多态表现。
本文早期发布于个人 CSDN 博客:查看原文