亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
Enter static: Late Static Bindings
Practical Use Cases for static
1. Static Factory Methods
2. Method Chaining with Inheritance
Caveats and Limitations
Summary
首頁 后端開發(fā) php教程 靜態(tài)與自我:PHP中的晚期靜態(tài)綁定

靜態(tài)與自我:PHP中的晚期靜態(tài)綁定

Jul 26, 2025 am 09:50 AM
PHP Syntax

當(dāng)在繼承中使用self調(diào)用靜態(tài)方法時,它始終指向定義方法的類,而非實際調(diào)用的類,導(dǎo)致無法按預(yù)期調(diào)用子類重寫的方法;而static采用后期靜態(tài)綁定,能在運行時正確解析到實際調(diào)用的類。1. self是早期綁定,指向代碼所在類;2. static是后期綁定,指向運行時調(diào)用類;3. 使用static可實現(xiàn)靜態(tài)工廠方法,自動返回子類實例;4. static支持方法鏈中繼承屬性的正確解析;5. LSB僅適用于靜態(tài)方法和屬性,不適用于常量;6. 在可繼承的類中應(yīng)優(yōu)先使用static以提升靈活性和可擴展性,該做法在現(xiàn)代PHP中被廣泛推薦。

Static vs. Self: Unraveling Late Static Bindings in PHP

When working with inheritance in PHP, you’ve probably encountered self and wondered why sometimes it doesn’t behave the way you’d expect — especially when calling static methods from child classes. This is where Late Static Bindings (LSB) come into play, and the difference between self and static becomes crucial.

The Problem with self

self in PHP refers to the class where the method is defined, not necessarily the one that’s calling it. This means it’s early bound — resolved at compile time, not runtime.

Consider this example:

class ParentClass {
    public static function who() {
        echo "ParentClass\n";
    }

    public static function callWho() {
        self::who();
    }
}

class ChildClass extends ParentClass {
    public static function who() {
        echo "ChildClass\n";
    }
}

ChildClass::callWho(); // Outputs: "ParentClass"

Even though we’re calling callWho() on ChildClass, it outputs ParentClass. Why? Because self::who() inside ParentClass always refers to ParentClass::who(), regardless of the calling context.

This behavior is often not what you want when designing extensible class hierarchies.


Enter static: Late Static Bindings

PHP 5.3 introduced Late Static Bindings, allowing static to refer to the class that was called at runtime — not where the method is defined.

Let’s tweak the example using static instead of self:

class ParentClass {
    public static function who() {
        echo "ParentClass\n";
    }

    public static function callWho() {
        static::who(); // Note: static instead of self
    }
}

class ChildClass extends ParentClass {
    public static function who() {
        echo "ChildClass\n";
    }
}

ChildClass::callWho(); // Outputs: "ChildClass"

Now it prints ChildClass. That’s because static::who() is resolved at runtime based on the actual class used in the call — this is late binding.

? Rule of thumb:

  • self → refers to the current class (where the code is written)
  • static → refers to the called class (which may be a child)

Practical Use Cases for static

1. Static Factory Methods

You can create a base factory method that returns instances of the correct child class:

class Model {
    public static function create() {
        return new static(); // Returns instance of called class
    }
}

class User extends Model {
    // Inherits create(), but returns User instance
}

$user = User::create(); // Actually a User object
var_dump($user instanceof User); // true

Without static, you’d have to override create() in every child class.

2. Method Chaining with Inheritance

class QueryBuilder {
    protected static $table;

    public static function all() {
        echo "Selecting from " . static::$table . "\n";
    }
}

class User extends QueryBuilder {
    protected static $table = 'users';
}

User::all(); // Outputs: "Selecting from users"

Again, static::$table resolves to User::$table, not QueryBuilder::$table.


Caveats and Limitations

  • LSB only works with static method and property calls.
  • It doesn’t apply to constants (self::CONST vs static::CONST still refers to the class where it’s defined).
  • Be cautious when using static in final classes — no inheritance, so self and static behave the same.
  • Performance difference is negligible; prioritize clarity and correct behavior.

Summary

Keyword Binding Time Refers To
self Early (compile time) Class where method is defined
static Late (runtime) Actual class called

Use static when you want inherited methods to respect the calling class’s implementation — especially in abstract bases, factories, or fluent interfaces.

In modern PHP, favor static over self when working with static methods in inheritable classes. It makes your code more flexible and intuitive.

Basically: if you're building something meant to be extended, static is probably the right choice.

以上是靜態(tài)與自我:PHP中的晚期靜態(tài)綁定的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
PHP 8屬性的簡介:用結(jié)構(gòu)化元數(shù)據(jù)代替DocBlocks PHP 8屬性的簡介:用結(jié)構(gòu)化元數(shù)據(jù)代替DocBlocks Jul 25, 2025 pm 12:27 PM

php8attributesreplaceplacecblocksformetAdataByProvidingType-safe,nenativeSuppportedAnnotations.1.AttriButesRedEarsedefinedused#[attribute] [attribute]和cantargetClasses,方法,方法,屬性等

PHP語法容易嗎? PHP語法容易嗎? Jul 17, 2025 am 04:12 AM

是的,phpsyntaxiseasy,尤其是forbeginners,因為炎是可見的,可以整合willwithhtml,andrequiresminimalsetup.itssyntaxisstraightforward,允許使用$ forvariobles,semicolonsolonsolonsolonsolonsolonsolonsolonforstatements,允許directembedectembedembedectembedembedembedembednothtmlwithtags

掌握PHP陣列破壞性和傳播操作員 掌握PHP陣列破壞性和傳播操作員 Jul 25, 2025 am 04:44 AM

PHP的數(shù)組解構(gòu)和展開運算符可通過簡潔語法提升代碼可讀性與靈活性。1.數(shù)組解構(gòu)支持從索引和關(guān)聯(lián)數(shù)組中提取值,如[$first,$second]=$colors可分別賦值;可通過空占位符跳過元素,如[,,$third]=$colors;關(guān)聯(lián)數(shù)組解構(gòu)需用=>匹配鍵,如['name'=>$name]=$user,支持重命名變量和設(shè)置默認(rèn)值以應(yīng)對缺失鍵。2.展開運算符(...)可將數(shù)組展開合并,如[...$colors,'blue'],支持多數(shù)組合并及關(guān)聯(lián)數(shù)組覆蓋,但后續(xù)鍵會覆蓋前者,且不重

利用現(xiàn)代PHP中的命名論證和構(gòu)造屬性促進 利用現(xiàn)代PHP中的命名論證和構(gòu)造屬性促進 Jul 24, 2025 pm 10:28 PM

php8.0'snameDargumentsAndConstructorPropertyPromotionimprovecodeclarityAndReduceBoilerplate:1.1.NamedArgumentsLetyOupSparameTersByname,增強可讀性和可讀取性andallowingFlexibleOrder; 2.ConstructorpropertyProperpropyPropyPromotyPromotionautomotationalomationalomatialicallicallialicalCeratesandassandassAssAssAssAssAsspropertiessiessiespropertiessiessiessiessiessiessiessiessiessiessiessies

靜態(tài)與自我:PHP中的晚期靜態(tài)綁定 靜態(tài)與自我:PHP中的晚期靜態(tài)綁定 Jul 26, 2025 am 09:50 AM

當(dāng)在繼承中使用self調(diào)用靜態(tài)方法時,它始終指向定義方法的類,而非實際調(diào)用的類,導(dǎo)致無法按預(yù)期調(diào)用子類重寫的方法;而static采用后期靜態(tài)綁定,能在運行時正確解析到實際調(diào)用的類。1.self是早期綁定,指向代碼所在類;2.static是后期綁定,指向運行時調(diào)用類;3.使用static可實現(xiàn)靜態(tài)工廠方法,自動返回子類實例;4.static支持方法鏈中繼承屬性的正確解析;5.LSB僅適用于靜態(tài)方法和屬性,不適用于常量;6.在可繼承的類中應(yīng)優(yōu)先使用static以提升靈活性和可擴展性,該做法在現(xiàn)代PH

了解php中的變異功能和參數(shù)解開。 了解php中的變異功能和參數(shù)解開。 Jul 25, 2025 am 04:50 AM

PHP的可變函數(shù)和參數(shù)解包通過splat操作符(...)實現(xiàn),1.可變函數(shù)使用...$params收集多個參數(shù)為數(shù)組,必須位于參數(shù)列表末尾,可與必需參數(shù)共存;2.參數(shù)解包使用...$array將數(shù)組展開為獨立參數(shù)傳入函數(shù),適用于數(shù)值索引數(shù)組;3.兩者可結(jié)合使用,如在包裝函數(shù)中傳遞參數(shù);4.PHP8 支持解包關(guān)聯(lián)數(shù)組時匹配具名參數(shù),需確保鍵名與參數(shù)名一致;5.注意避免對非可遍歷數(shù)據(jù)使用解包,防止致命錯誤,并注意參數(shù)數(shù)量限制。這些特性提升了代碼靈活性和可讀性,減少了對func_get_args()等

揭開PHP的三元,無效合并和無效操作員 揭開PHP的三元,無效合并和無效操作員 Jul 25, 2025 pm 04:48 PM

Theternaryoperator(?:)isusedforsimpleif-elselogic,returningoneoftwovaluesbasedonacondition;2.Thenullcoalescingoperator(??)returnstheleftoperandifitisnotnullorundefined,otherwisetherightoperand,makingitidealforsettingdefaultswithoutbeingaffectedbyfals

php匿名函數(shù)與箭頭函數(shù):語法深度潛水 php匿名函數(shù)與箭頭函數(shù):語法深度潛水 Jul 25, 2025 pm 04:55 PM

箭頭函數(shù)適用于單一表達式、簡單回調(diào)和提升可讀性的場景;2.匿名函數(shù)適用于多行邏輯、復(fù)雜控制流、引用外部變量和使用yield生成器的場景;因此應(yīng)根據(jù)具體需求選擇:簡單場景優(yōu)先使用箭頭函數(shù)以提高代碼簡潔性,復(fù)雜場景則使用匿名函數(shù)以獲得完整功能支持。

See all articles