static 關鍵字在 PHP 中用於宣告靜態屬性與方法,PHP 5.3 引入的靜態晚期綁定(Late Static Binding, LSB)解決了繼承體系中 self:: 無法正確參考子類別靜態成員的問題。本文深入解析 static 特性、self 與 static 的關鍵差異。
ClassName::$prop、ClassName::method())。-> 存取(但靜態方法可透過物件呼叫)。$this,無法存取非靜態成員。<?php
class Vehicle {
protected static $name = 'This is a Vehicle';
public static function what_vehicle() {
echo get_called_class() . "\n";
echo self::$name . "\n"; // 編譯期綁定:永遠指向 Vehicle::$name
}
}
class Sedan extends Vehicle {
protected static $name = 'This is a Sedan';
}
Sedan::what_vehicle();
// 輸出:
// Sedan
// This is a Vehicle ← self 綁定父類別
<?php
class Vehicle {
protected static $name = 'This is a Vehicle';
public static function what_vehicle() {
echo get_called_class() . "\n";
echo static::$name . "\n"; // 執行期綁定:指向實際被呼叫的類別 Sedan
}
}
class Sedan extends Vehicle {
protected static $name = 'This is a Sedan';
}
Sedan::what_vehicle();
// 輸出:
// Sedan
// This is a Sedan ← static 晚期綁定至子類別
:: 左側的類別)。self::、parent::、static::、forward_static_call() 屬於「轉發呼叫」,不會更新此記錄。get_called_class() 可取得實際被呼叫的類別名稱。static:: 代表當前晚期綁定的範圍。static::tableName(),子類別覆寫回傳各自資料表名稱。static::create(),利用 LSB 實例化正確的子類別。self:: 為編譯期綁定(指向定義該方法的類別),static:: 為執行期晚期綁定(指向實際呼叫的類別)。善用 LSB 能編寫更彈性、可擴充的繼承體系程式碼。