在PHP中实现多态性可以通过继承和接口来实现。具体实现步骤如下:
abstract class Shape {
abstract public function calculateArea();
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
class Rectangle extends Shape {
private $length;
private $width;
public function __construct($length, $width) {
$this->length = $length;
$this->width = $width;
}
public function calculateArea() {
return $this->length * $this->width;
}
}
class ShapeFactory {
public static function createShape($type, $params) {
switch($type) {
case 'circle':
return new Circle($params['radius']);
break;
case 'rectangle':
return new Rectangle($params['length'], $params['width']);
break;
default:
throw new Exception('Invalid shape type');
}
}
}
$circle = ShapeFactory::createShape('circle', ['radius' => 5]);
echo $circle->calculateArea(); // 输出78.54
$rectangle = ShapeFactory::createShape('rectangle', ['length' => 5, 'width' => 3]);
echo $rectangle->calculateArea(); // 输出15
通过以上步骤,我们实现了多态性,不同的子类对象调用相同的方法,实现了不同的行为。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。