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