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