您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。