抽象類別是物件導向設計中定義「契約」與「共通行為」的關鍵機制。它無法被實例化,只能被繼承,強制子類別實作抽象方法,確保介面一致性。
<?php
abstract class ClassName {
// 抽象方法:只有宣告,無主體 (大括號)
abstract protected function methodName($param1, $param2);
// 也可包含具體方法 (非抽象)
public function commonMethod() {
echo '共通功能';
}
}
?>
{ })。implements。<?php
abstract class Shape {
// 契約:所有形狀必須能計算面積
abstract protected function getArea(): float;
// 共通方法:取得名稱
public function getName(): string {
return static::class; // 晚期靜態綁定,取得實際子類別名稱
}
}
class Rectangle extends Shape {
private float $width;
private float $height;
public function __construct(float $width, float $height) {
$this->width = $width;
$this->height = $height;
}
// 實作抽象方法
protected function getArea(): float {
return $this->width * $this->height;
}
}
class Circle extends Shape {
private float $radius;
public function __construct(float $radius) {
$this->radius = $radius;
}
protected function getArea(): float {
return M_PI * $this->radius ** 2;
}
}
// 使用
$shapes = [
new Rectangle(10, 20),
new Circle(5),
];
foreach ($shapes as $shape) {
printf('%s 面積: %.2f', $shape->getName(), $shape->getArea()) . PHP_EOL;
}
// 輸出:
// Rectangle 面積: 200.00
// Circle 面積: 78.54
?>
| 特性 | 抽象類別 | 介面 |
|---|---|---|
| 關鍵字 | abstract class | interface |
| 方法主體 | 可包含具體方法 | 全部為抽象方法 (PHP 8.0 前) |
| 屬性 | 可定義屬性 (含 static) | 僅常數 |
| 建構子 | 可定義 __construct | 不可 |
| 繼承/實作 | extends (單一) | implements (多重) |
| 適用場景 | 「是一種」關係,共享程式碼與狀態 | 「能做某事」契約,多型行為 |