在 PHP 中,靜態類是不允許被實例化的,也就是說我們不能使用 new 關鍵字來創建靜態類的實例。但是,我們可以使用靜態方法和屬性。關于靜態類的繼承和覆蓋,有以下規則:
靜態屬性和方法的繼承: 當一個子類繼承一個父類時,子類會自動繼承父類的所有靜態屬性和方法。如果子類中定義了與父類相同名稱的靜態屬性或方法,那么子類將覆蓋父類的靜態屬性和方法。
靜態方法的重寫:
在子類中,可以通過使用 public static function methodName() 的形式來重寫父類的靜態方法。當調用該方法時,將執行子類中的版本,而不是父類中的版本。
使用 late static binding:
late static binding 是一種在運行時確定要調用哪個類的方法的技術。在子類中,可以使用 static::methodName() 來調用父類中被覆蓋的方法。這可以確保始終調用正確的版本,而不管實際調用的對象類型如何。
示例:
class ParentClass {
protected static $value = 'Parent';
public static function getValue() {
return static::$value;
}
}
class ChildClass extends ParentClass {
protected static $value = 'Child';
public static function getValue() {
return static::$value;
}
}
echo ParentClass::getValue(); // 輸出 "Parent"
echo ChildClass::getValue(); // 輸出 "Child"
在這個例子中,ChildClass 重寫了父類 ParentClass 的靜態方法 getValue()。當我們調用 ChildClass::getValue() 時,它返回 “Child”,而不是 “Parent”。這是因為 late static binding 確保了調用的是子類中的版本。