溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP的new static和new self是什么

發(fā)布時(shí)間:2020-11-06 14:08:53 來源:億速云 閱讀:151 作者:小新 欄目:編程語(yǔ)言

PHP的new static和new self是什么?這個(gè)問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個(gè)問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!

下面我們舉個(gè)栗子:

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 這個(gè) class, 可以總結(jié)如下:

self 返回的是 new self 中關(guān)鍵字 new 所在的類中,比如這里例子的 :

public static function getSelf() {
    return new self(); // new 關(guān)鍵字在 Father 這里
}

始終返回 Father。

new static

static 則上面的基礎(chǔ)上,更聰明一點(diǎn)點(diǎn):static 會(huì)返回執(zhí)行 new static() 的類,比如 Son 執(zhí)行 get_class(Son::getStatic()) 返回的是 Son, Father 執(zhí)行 get_class(Father::getStatic()) 返回的是 Father

而在沒有繼承的情況下,可以認(rèn)為 new self 和 new static 是返回相同的結(jié)果。

感謝各位的閱讀!看完上述內(nèi)容,你們對(duì)PHP的new static和new self是什么大概了解了嗎?希望文章內(nèi)容對(duì)大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI