多型意指「一個介面,多種實作」。同一操作作用於不同類別實例,產生不同執行結果。實務上可將不同子類別物件視為同一父類別/介面處理,屏蔽差異,寫出通用程式碼,靈活應對需求變更。
<?php
/**
* 介面定義:規範必須實作的方法,不包含實作細節
* 所有方法預設為 public
*/
interface Shape {
public function draw();
}
/**
* 三角形實作 Shape 介面
*/
class Triangle implements Shape {
public function draw() {
echo "Triangle::draw()\n";
}
}
/**
* 矩形實作 Shape 介面
*/
class Rectangle implements Shape {
public function draw() {
echo "Rectangle::draw()\n";
}
}
/**
* 通用繪圖測試類別:接受任何實作 Shape 介面的物件
*/
class TestPoly {
public function drawNow(Shape $shape) {
$shape->draw(); // 多型:具體行為由傳入物件決定
}
}
// 客戶端程式碼
$test = new TestPoly();
$test->drawNow(new Triangle()); // 輸出: Triangle::draw()
$test->drawNow(new Rectangle()); // 輸出: Rectangle::draw()
?>
drawNow(Shape $shape) 限定參數必須實作 Shape 介面,編譯期檢查。draw() 由傳入物件的真實類別決定(動態綁定)。TestPoly 或客戶端程式碼。interface Loggable { public function log(); }
interface Serializable { public function serialize(); }
class MyClass implements Shape, Loggable, Serializable {
public function draw() { /* ... */ }
public function log() { /* ... */ }
public function serialize() { /* ... */ }
}
PHP 支援單一類別實作多個介面,進一步增強設計彈性。