在PHP中实现多态性可以使用抽象类和接口。
使用抽象类实现多态性的示例代码:
<?php abstract class Shape { abstract function getArea(); } class Circle extends Shape { private $radius; function __construct($radius){ $this->radius = $radius; } public function getArea(){ return $this->radius * $this->radius * pi(); } } class Square extends Shape { private $length; function __construct($length){ $this->length = $length; } public function getArea(){ return $this->length * $this->length; } } $shapes = array(new Circle(2), new Square(5)); foreach($shapes as $shape){ echo "Area of shape is " . $shape->getArea() . "<br/>"; } ?>
使用接口实现多态性的示例代码:
<?php interface Shape { public function getArea(); } class Circle implements Shape { private $radius; function __construct($radius){ $this->radius = $radius; } public function getArea(){ return $this->radius * $this->radius * pi(); } } class Square implements Shape { private $length; function __construct($length){ $this->length = $length; } public function getArea(){ return $this->length * $this->length; } } $shapes = array(new Circle(2), new Square(5)); foreach($shapes as $shape){ echo "Area of shape is " . $shape->getArea() . "<br/>"; } ?>