如何在PHP中实现多态性?

我想了解如何在PHP中实现多态性。我的理解是,多态性是指同一个函数名字,能够根据参数的不同而产生不同的处理结果。在PHP中,可以使用抽象类和接口来实现多态性。抽象类定义了一个基类,子类可以继承基类并实现不同的方法,从而实现多态性。而接口是指定了一些方法,类实现这些方法后就可以实现该接口的多态性。我想了解如何使用抽象类和接口来实现多态性,并希望有详细的示例代码来帮助我更好地理解。

提问时间:2023-05-19 12:26:06 编辑时间:2023-05-19 12:26:08 提问者: 雨夜迷情
  • Night_Crawler
    5

    在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/>"; } ?>

    回答时间:2023-05-19 12:26:11