「以不同形式、階段或類型出現,而不存在根本區別。」—— 同一介面/基類,不同具體實作,客戶端統一呼叫,無需關心具體類別。
<?php
interface Demo {
const NAME = 'WangZhengYi';
const AGE = 25;
public function fun1(): void;
public function fun2(): void;
}
// 實作 A:學生身份
class One implements Demo {
public function fun1(): void { echo self::NAME . " 就讀於中國傳媒大學\n"; }
public function fun2(): void { echo self::NAME . " 的年齡是 " . self::AGE . "\n"; }
}
// 實作 B:實習生身份
class Two implements Demo {
public function fun1(): void { echo self::NAME . " 在北京靈創眾和科技有限公司實習中\n"; }
public function fun2(): void { echo self::NAME . " 去年的年齡是 24\n"; }
}
// 客戶端:只依賴 Demo 介面
function introduce(Demo $obj): void {
$obj->fun1();
$obj->fun2();
}
introduce(new One()); // 輸出學生資訊
introduce(new Two()); // 輸出實習資訊
?>
| 支柱 | 說明 | PHP 實現 |
|---|---|---|
| 介面/抽象基類 | 定義統一契約 | interface / abstract class |
| 繼承/實作 | 具體類別實現契約 | implements / extends |
| 向上轉型 | 以父類型持有子物件 | 參數型別宣告、陣列存儲、容器注入 |
<?php
// 1. 統一介面
interface PaymentGateway {
public function charge(float $amount, string $currency): bool;
public function refund(string $transactionId): bool;
}
// 2. 多種實作
class StripeGateway implements PaymentGateway { /* ... */ }
class PayPalGateway implements PaymentGateway { /* ... */ }
class OfflineGateway implements PaymentGateway { /* ... */ }
// 3. 工廠根據配置產生具體實作
class GatewayFactory {
public static function create(string $type): PaymentGateway {
return match ($type) {
'stripe' => new StripeGateway(),
'paypal' => new PayPalGateway(),
'offline' => new OfflineGateway(),
default => throw new InvalidArgumentException("Unknown gateway: $type"),
};
}
}
// 4. 業務邏輯完全不知具體閘道
class OrderService {
public function __construct(private PaymentGateway $gateway) {}
public function process(float $amt): bool {
return $this->gateway->charge($amt, 'USD');
}
}
// 5. 組裝 (可由 DI 容器自動完成)
$gateway = GatewayFactory::create(config('payment.default'));
$service = new OrderService($gateway);
$service->process(199.00);
?>
<?php
class ReportExporter {
private ExportStrategy $strategy;
public function setStrategy(ExportStrategy $s): void { $this->strategy = $s; }
public function export(array $data): string {
return $this->strategy->render($data);
}
}
interface ExportStrategy {
public function render(array $data): string;
}
class CsvStrategy implements ExportStrategy {
public function render(array $data): string { /* CSV 邏輯 */ return "csv"; }
}
class PdfStrategy implements ExportStrategy {
public function render(array $data): string { /* PDF 邏輯 */ return "pdf"; }
}
class ExcelStrategy implements ExportStrategy {
public function render(array $data): string { /* Excel 邏輯 */ return "xlsx"; }
}
// 控制器根據請求參數動態切換
$exporter = new ReportExporter();
$exporter->setStrategy(match ($_GET['format'] ?? 'csv') {
'pdf' => new PdfStrategy(),
'excel' => new ExcelStrategy(),
default => new CsvStrategy(),
});
echo $exporter->export($reportData);
?>
OrderServicePaymentGateway,不依賴具體 StripeGatewayMockGateway 隔離外部依賴多型不只是「同名方法不同行為」,更是「面向介面編程」的基石。掌握 interface + implements + 依賴注入,能讓 PHP 專案從「寫腳本」進化為「做架構」,實現高內聚、低耦合、可持續演進的代碼庫。