PHP 5.3 引入「靜態延遲綁定」,new static() 與 new self() 在繼承場景下行為截然不同。本文通過代碼對比、底層原理解析、實戰模式示範,助你準確選用。
| 關鍵字 | 綁定時機 | 指向類別 | PHP版本 |
|---|---|---|---|
self | 編譯期 (早期綁定) | 定義該代碼的類別 (寫在哪屬於哪) | >= 5.0 |
static | 執行期 (延遲綁定) | 實際調用的類別 (誰調用屬於誰) | >= 5.3 |
解析:
self 在 Person 類中定義 → 永遠指向 Personstatic 在 WangBaoqiang::getStatic() 調用 → 指向 WangBaoqiang進階場景:非靜態方法中的實例化
create1())); // WangBaoqiang var_dump(get_class($obj->create2())); // WangBaoqiang ?>選用決策樹
- 需要當前類別實例 (不考慮繼承) →
new self()- 需要調用者類別實例 (支援繼承多態) →
new static()- PHP < 5.3 環境 →
new self()或new get_called_class()- 非靜態方法中 →
new static()或new get_class($this)與 $this 的關係
static 類似 $this 的靜態版本:代表「當前實例所屬類別」$this 僅實例方法可用;static 靜態/實例方法均可用static 可存取靜態屬性/方法/常數;$this 存取實例成員// ❌ 錯誤:self 在父類引用子類常數
class ParentClass {
const TYPE = 'parent';
public static function getType() { return self::TYPE; }
}
class ChildClass extends ParentClass {
const TYPE = 'child';
}
ChildClass::getType(); // 返回 'parent' (非預期)
// ✅ 正確:static 延遲綁定
class ParentClass {
const TYPE = 'parent';
public static function getType() { return static::TYPE; }
}
ChildClass::getType(); // 返回 'child' (正確)