欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP的new static和new self的區(qū)別與使用

 更新時間:2019年11月27日 10:52:33   作者:曉軒  
這篇文章主要介紹了PHP的new static和new self的區(qū)別與使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

下面我們舉個栗子:

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, 可以總結(jié)如下:
self 返回的是 new self 中關(guān)鍵字 new 所在的類中,比如這里例子的 :

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

始終返回 Father。

new static

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

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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論