亚洲国产日韩欧美一区二区三区,精品亚洲国产成人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
首頁(yè) 後端開(kāi)發(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)方法時(shí),它始終指向定義方法的類,而非實(shí)際調(diào)用的類,導(dǎo)致無(wú)法按預(yù)期調(diào)用子類重寫(xiě)的方法;而static採(cǎi)用後期靜態(tài)綁定,能在運(yùn)行時(shí)正確解析到實(shí)際調(diào)用的類。 1. self是早期綁定,指向代碼所在類;2. static是後期綁定,指向運(yùn)行時(shí)調(diào)用類;3. 使用static可實(shí)現(xiàn)靜態(tài)工廠方法,自動(dòng)返回子類實(shí)例;4. static支持方法鏈中繼承屬性的正確解析;5. LSB僅適用於靜態(tài)方法和屬性,不適用於常量;6. 在可繼承的類中應(yīng)優(yōu)先使用static以提升靈活性和可擴(kuò)展性,該做法在現(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)綁定的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門話題

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

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

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

是的,phpsyntaxiseasy,尤其是forbeginners,因?yàn)檠资强梢?jiàn)的,可以整合willwithhtml,andrequiresminimalsetup.itssyntaxisstraightforward,允許使用$ forvariobles,semicolonsolonsolonsolonsolonsolonsolonsolonforstatements,允許directembedectembedembedectembedembedembedembednothtmlwithtags

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

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

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

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

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

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

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

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

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

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

揭開(kāi)PHP的三元,無(wú)效合併和無(wú)效操作員 揭開(kāi)PHP的三元,無(wú)效合併和無(wú)效操作員 Jul 25, 2025 pm 04:48 PM

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

See all articles