首頁  >  文章  >  後端開發  >  區別PHP中new self() 和 new static()

區別PHP中new self() 和 new static()

coldplay.xixi
coldplay.xixi轉載
2020-06-08 10:01:372544瀏覽

區別PHP中new self() 和 new static()

PHP中new self() 和new static() 的差異

new static() 是在php5 .3版本引入的新特性

new static 和new self() 都是new 一個物件

直接看程式碼

class Father
{
    public function getNewFather()
    {
        return new self();
    }
  
    public function getNewCaller()
    {
        return new static();
    }
}
  
$f = new Father();
  
var_dump(get_class($f->getNewFather())); // Father
var_dump(get_class($f->getNewCaller())); // Father

getNewFather和getNewCaller 都是回傳的Father 這個實列

到這裡看起來像new self() 還是new static() 是沒有差別的

接著看下面的範例

class Sun1 extends Father{
  
}
  
$sun1 = new Sun1();
  
var_dump($sun1->getNewFather()); // object(Father)#4 (0) { }
var_dump($sun1->getNewCaller()); // object(Sun1)#4 (0) { }

getNewFather 回傳的是Father的實列,

getNewCaller 傳回的是呼叫者的實列

他們的區別只有在繼承中才能體現出來、如果沒有任何繼承、那麼二者沒有任何區別

new self() 傳回的實列是不會變的,無論誰去調用,都傳回的一個類別的實列,

new static則是由呼叫者決定的。

推薦教學:《PHP影片教學

以上是區別PHP中new self() 和 new static()的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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