最近在一個視頻的評論被問到一個小問題:這裏選擇用static 而不是self有特殊的考慮麼?或者咱們能夠這樣轉換一下問題:php
PHP 的 new static 和 new self 具體有什麼?app
視頻地址 https://www.codecasts.com/ser...phpstorm
其實這個來看一個例子應該就很清晰了:oop
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,能夠總結以下:spa
1.sel
f 返回的是 new self
中關鍵字 new
所在的類中,好比這裏例子的 :code
public static function getSelf() { return new self(); // new 關鍵字在 Father 這裏 }
始終返回 Father
。orm
2.static
則上面的基礎上,更聰明一點點:static
會返回執行 new static()
的類,好比 Son
執行 get_class(Son::getStatic())
返回的是 Son
, Father
執行 get_class(Father::getStatic())
返回的是 Father
視頻
而在沒有繼承的狀況下,能夠認爲 new self
和 new static
是返回相同的結果。blog
Tips: 能夠用一個好的 IDE 來直接看註釋。好比 PhpStorm:繼承
Happy Hacking