1. 程式人生 > >new self() 和 new static() 的區別

new self() 和 new static() 的區別

1、new static()是在php5.3版本引入的新特性
2、無論是 new static 還是 new self() 都是 new 一個物件
3、這兩個方法new 出來的物件 有什麼區別呢?說白了就是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 的區別了

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

 然後 new self() 返回的實列是不會變的,無論誰去呼叫,都返回的一個類的實列,
 而 new static則是由呼叫者決定的。