Strict Standards: Declaration of Child::method() should be compatible with Parent::method($param) in ...
或 PHP 7.0+ 升級為 Error (致命錯誤):
Fatal error: Declaration of Child::method() must be compatible with Parent::method($param)
子類重寫方法的簽名 (參數列表、返回類型) 與父類/介面不兼容。 PHP 5.3+ 引入 E_STRICT,PHP 7.0+ 提升為 TypeError,強制執行 里氏替換原則 (LSP):子類必須能無縫替換父類,方法簽名必須「至少同樣寬鬆」。
| 父類簽名 | 子類簽名 | 兼容? | 說明 | |
|---|---|---|---|---|
foo(int $a) | foo(int $a) | ✅ | 完全一致 | |
foo(int $a) | foo(int $a = 0) | ✅ | 子類增加默認值 (更寬鬆) | |
foo(int $a = 0) | foo(int $a) | ❌ | 子類移除默認值 (更嚴格) — 破壞 LSP | |
foo(int $a) | foo(int $a, int $b = 0) | ✅ | 子類增加可選參數 | |
foo(int $a, int $b = 0) | foo(int $a) | ❌ | 子類減少參數 | |
foo(int ...$args) | foo(int $a, int $b) | ❌ | 可變參數 vs 固定參數不兼容 | |
foo(): int | foo(): int | ✅ | 返回類型协变 (PHP 7.4+) | |
foo(): ParentClass | foo(): ChildClass | ✅ | 返回類型協變 (子類型) | |
foo(): ChildClass | foo(): ParentClass | ❌ | 返回類型逆變 (父類型) — 違反 LSP | |
foo(): void | foo(): int | ❌ | void 不可協變 | |
foo(iterable $items) | foo(array $items) | ❌ | 參數類型逆變 (array 更嚴格) | |
foo(array $items) | foo(iterable $items) | ✅ | 參數類型協變 (iterable 更寬鬆) |
// ❌ 錯誤
class Parent {
public function setData(string $key, $value) {}
}
class Child extends Parent {
public function setData($value) {} // 少了 $key
}
// ✅ 修復:補齊參數,或標記為可選
class Child extends Parent {
public function setData(string $key, $value = null) {} // 兼容
}
interface Repository {
public function findById(int $id): ?Entity;
}
class UserRepository implements Repository {
// ❌ 返回類型不兼容 (Entity 非 ?Entity)
public function findById(int $id): Entity { ... }
// ✅ 修復
public function findById(int $id): ?Entity { ... }
}
class BaseModel {
public function __construct(array $attributes = []) {}
}
class User extends BaseModel {
// ❌ 增加必填參數
public function __construct(string $role, array $attributes = []) {}
// ✅ 修復:所有新增參數必須有默認值
public function __construct(array $attributes = [], string $role = 'user') {}
}
class A {
public static function boot() {}
}
class B extends A {
// ❌ 靜態 vs 非靜態 不兼容
public function boot() {}
// ✅ 保持一致
public static function boot() {}
}
網上流傳「父類必須在子類前定義」可避免此錯誤,這是錯誤的。PHP 編譯器會先解析所有類結構再執行,定義順序不影響簽名檢查。真正原因是 spl_autoload_register 自動加載時,若子類文件先被加載 (因依賴關係),而父類尚未加載,PHP 會臨時創建一個「不完整」的父類存根,導致後續檢查失敗。解決:確保自動加載器能正確解析依賴順序,或手動 require 父類。
「Declaration must be compatible with」不是阻礙,而是架構護欄。它強迫你遵守里氏替換原則,保證多態的安全性。理解協變/逆變規則、養成介面先行習慣、接入靜態分析,即可從根源消除此類錯誤,編寫出真正可擴展、可維護的面向對象代碼。