首頁  >  文章  >  後端開發  >  PHP 的 new static 和 new self

PHP 的 new static 和 new self

藏色散人
藏色散人轉載
2019-09-26 09:18:122492瀏覽

下面我們舉個栗子:

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 的 new static 和 new self的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:dmzfa。如有侵權,請聯絡admin@php.cn刪除