<?php // 多态性 interface Shape { public function calcArea(); }
// 下面两个类都实现了calcArea方法 class Rectange implements Shape { public $x, $y, $width, $height; public function calcArea() { return $this->width * $this->height; } }
class Circle implements Shape { const PI = 3.14; public $x, $y, $r; public function calcArea() { return $this->r * $this->r * self::PI; } }
// 多态性的核心思想:用基类的变量去调用子类的方法 function display_area(Shape $shape) { echo '该图形的面积是: ' . $shape->calcArea() . '<br>'; }
$r = new Rectange(); $r->width = 400; $r->height = 380; display_area($r);
$c = new Circle(); $c->r = 4.8; display_area($c); ?>
运行结果: 该图形的面积是: 152000 该图形的面积是: 72.3456
|