PHP 5 完整支援抽象類別、介面與型別檢查,奠定契約式設計基礎。本文系統整理核心概念與實戰範例。
abstract 關鍵字宣告。abstract class Car {
abstract public function getMaxSpeed();
}
class Roadster extends Car {
private $speed;
public function setSpeed($speed = 0) { $this->speed = $speed; }
public function getMaxSpeed() { return $this->speed; }
}
class Street {
private $speedLimit;
private $cars = [];
public function __construct($limit = 200) { $this->speedLimit = $limit; }
protected function isStreetLegal(Car $car) {
return $car->getMaxSpeed() < $this->speedLimit;
}
public function addCar(Car $car) {
if ($this->isStreetLegal($car)) {
echo "The Car was allowed on the road.";
$this->cars[] = $car;
} else {
echo "The Car is too fast and was not allowed on the road.";
}
}
}
$porsche = new Roadster();
$porsche->setSpeed(340);
$street = new Street(80);
$street->addCar($porsche); // 輸出: The Car is too fast...
interface 定義,所有方法隱含 public abstract。implements 實作介面 (可實作多個)。extends)。I 開頭 (如 ISpeedInfo)。abstract class Car {
abstract public function setSpeed($speed = 0);
}
interface ISpeedInfo {
public function getMaxSpeed();
}
class Roadster extends Car implements ISpeedInfo {
private $speed;
public function setSpeed($speed = 0) { $this->speed = $speed; }
public function getMaxSpeed() { return $this->speed; }
}
instanceof 型別檢查$porsche = new Roadster();
var_dump($porsche instanceof Car); // true (繼承)
var_dump($porsche instanceof ISpeedInfo); // true (實作)
var_dump($porsche instanceof Roadster); // true (本身)
用途:確認物件型別、父類別關係、介面實作。
Design by Contract (DbC):在實作類別前先定義介面契約,包含先驗條件、後驗條件與不變式。優點:
| 特性 | 抽象類別 | 介面 |
|---|---|---|
| 關鍵字 | abstract class | interface |
| 繼承關鍵字 | extends | implements |
| 多重繼承 | 單一繼承 | 可實作多個 |
| 方法主體 | 可包含具體方法 | 全為抽象 (PHP 8 前) |
| 屬性 | 可定義屬性 | 僅常數 |
| 建構子 | 可定義 | 不可定義 |
這是 PHP 設計選擇,介面提供了更安全的組合方式。