在面向對象編程中,多態性是指不同對象可以對同一消息做出不同響應的能力。在PHP中,多態性主要通過接口和繼承來實現。本文將通過實際代碼示例,詳細解析PHP中的多態性概念。
首先,我們創建一個接口Shape,其中包含一個calculateArea方法:
interface Shape {
public function calculateArea();
}
接著,我們創建兩個類Circle和Square,它們都實現Shape接口:
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return round(pi() * pow($this->radius, 2), 2);
}
}
class Square implements Shape {
private $sideLength;
public function __construct($sideLength) {
$this->sideLength = $sideLength;
}
public function calculateArea() {
return pow($this->sideLength, 2);
}
}
接下來,我們定義一個函數getShapeArea,該函數接受實現了Shape接口的對像作為參數,並調用其calculateArea方法:
function getShapeArea(Shape $shape) {
return $shape->calculateArea();
}
現在,我們可以創建Circle和Square對象,並使用getShapeArea函數計算它們的面積:
$circle = new Circle(5);
$square = new Square(4);
echo "圓的面積:" . getShapeArea($circle) . ";";
echo "正方形的面積:" . getShapeArea($square) . "。";
在這個示例中,Circle和Square類都實現了Shape接口,並覆蓋了calculateArea方法。通過傳入不同對像到getShapeArea函數,我們實現了多態性:同一函數對不同對象執行不同邏輯。
PHP中的多態性通過接口和繼承實現,使不同對象能夠對同一消息作出不同響應。這種機制提高了代碼的靈活性和可擴展性。合理利用多態性,可以簡化代碼結構,提高代碼復用性,並讓面向對象程序更具可維護性。