首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP new static() vs new self() 深度解析:靜態綁定、繼承行為差異、實戰選用指南

     編輯:PHP 綜合知識

PHP 5.3 引入「靜態延遲綁定」,new static() 與 new self() 在繼承場景下行為截然不同。本文通過代碼對比、底層原理解析、實戰模式示範,助你準確選用。

核心差異

關鍵字綁定時機指向類別PHP版本
self編譯期 (早期綁定)定義該代碼的類別 (寫在哪屬於哪)>= 5.0
static執行期 (延遲綁定)實際調用的類別 (誰調用屬於誰)>= 5.3

代碼對比演示

解析:

  • self 在 Person 類中定義 → 永遠指向 Person
  • static 在 WangBaoqiang::getStatic() 調用 → 指向 WangBaoqiang

實戰模式:工廠方法 / 活躍記錄基類



進階場景:非靜態方法中的實例化

create1())); // WangBaoqiang
var_dump(get_class($obj->create2())); // WangBaoqiang
?>

選用決策樹

  1. 需要當前類別實例 (不考慮繼承) → new self()
  2. 需要調用者類別實例 (支援繼承多態) → new static()
  3. PHP < 5.3 環境 → new self() 或 new get_called_class()
  4. 非靜態方法中 → 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' (正確)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved