PHP new static 和 new self詳解
最近在一個(gè)視頻的評(píng)論被問到一個(gè)小問題:這里選擇用static 而不是self有特殊的考慮么?或者我們可以這樣轉(zhuǎn)換一下問題:
PHP 的 new static 和 new self 具體有什么?
其實(shí)這個(gè)來看一個(gè)例子應(yīng)該就很清晰了:
class Father { public static function getSelf() { return new self(); } public static function getStatic() { return new static(); } } class Son extends Father {} echo get_class(Son::getSelf()); // Father echo get_class(Son::getStatic()); // Son echo get_class(Father::getSelf()); // Father echo get_class(Father::getStatic()); // Father
這里面注意這一行 get_class(Son::getStatic());
返回的是 Son
這個(gè) class,可以總結(jié)如下:
new self
1.self
返回的是 new self
中關(guān)鍵字 new
所在的類中,比如這里例子的 :
public static function getSelf() { return new self(); // new 關(guān)鍵字在 Father 這里 }
始終返回 Father
。
new static
2.static
則上面的基礎(chǔ)上,更聰明一點(diǎn)點(diǎn):static
會(huì)返回執(zhí)行 new static()
的類,比如 Son
執(zhí)行 get_class(Son::getStatic())
返回的是 Son
, Father
執(zhí)行 get_class(Father::getStatic())
返回的是 Father
而在沒有繼承的情況下,可以認(rèn)為 new self
和 new static
是返回相同的結(jié)果。
Tips: 可以用一個(gè)好的 IDE 來直接看注釋。比如 PhpStorm:
Happy Hacking
- PHP中new static()與new self()的區(qū)別異同分析
- php self,$this,const,static,->的使用
- php類中的$this,static,final,const,self這幾個(gè)關(guān)鍵字使用方法
- PHP中new static() 和 new self() 的區(qū)別介紹
- PHP中static關(guān)鍵字以及與self關(guān)鍵字的區(qū)別
- PHP面向?qū)ο笾衝ew self()與 new static()的區(qū)別淺析
- 淺談PHP中new self()和new static()的區(qū)別
- php類中static與self的使用區(qū)別淺析
相關(guān)文章
啟用Csrf后POST數(shù)據(jù)時(shí)出現(xiàn)的400錯(cuò)誤
這篇文章主要介紹了啟用Csrf后POST數(shù)據(jù)時(shí)出現(xiàn)的400錯(cuò)誤的相關(guān)資料,需要的朋友可以參考下2015-07-07PHP+MariaDB數(shù)據(jù)庫(kù)操作基本技巧備忘總結(jié)
這篇文章主要介紹了PHP+MariaDB數(shù)據(jù)庫(kù)操作基本技巧,結(jié)合實(shí)例形式總結(jié)分析了PHP+MariaDB數(shù)據(jù)庫(kù)連接、判斷以及基于PHP+MariaDB的用戶登陸、管理、刪除等相關(guān)操作實(shí)現(xiàn)技巧與注意事項(xiàng),需要的朋友可以參考下2018-05-05如何在symfony中導(dǎo)出為CSV文件中的數(shù)據(jù)
如果您需要在symfony中將數(shù)據(jù)庫(kù)中的數(shù)據(jù)導(dǎo)出為CSV文件,試試這個(gè)2011-10-10