下面我們舉個栗子:
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
new self
這里面注意這一行 get_class(Son::getStatic()); 返回的是 Son 這個 class, 可以總結如下:
self 返回的是 new self 中關鍵字 new 所在的類中,比如這里例子的 :
public static function getSelf() {
return new self(); // new 關鍵字在 Father 這里
}
始終返回 Father。
new static
static 則上面的基礎上,更聰明一點點:static 會返回執行 new static() 的類,比如 Son 執行 get_class(Son::getStatic()) 返回的是 Son, Father 執行 get_class(Father::getStatic()) 返回的是 Father
而在沒有繼承的情況下,可以認為 new self 和 new static 是返回相同的結果。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- PHP面向對象程序設計中的self、static、parent關鍵字用法分析
- php面向對象程序設計中self與static的區別分析
- PHP面向對象中new self()與 new static()的區別淺析
- 淺談PHP中new self()和new static()的區別
- PHP Class self 與 static 異同與使用詳解