對比 PHP 中 new static() 與 new self()

通過new static()與new self()都能產生實例對象,new static()是在PHP5.3版本中引入的新特性,本文對二者稍作對比。

一、當直接通過本類創建實例時

class Test
{
    public static function getIns()
    {
        $obj1 = new self();
        $obj2 = new static();
        return [$obj1, $obj2];
    }
}
$arr = Test::getIns();
var_dump(get_class($arr[0]) === get_class($arr[1])); // true

通過以上代碼可知,當直接從同一個類創建對象時,二者相同。

 

二、當子類繼承父類創建對象時

class Test
{
    public static function getIns()
    {
        $obj1 = new self();
        $obj2 = new static();
        return [$obj1, $obj2];
    }
}
class Test1 extends Test
{
    
}
class Test2 extends Test
{

}
$arr1 = Test1::getIns();
echo 'Test1類繼承Test類通過self產生實例的類名: ', get_class($arr1[0]), '<br>';    // Test
echo 'Test1類繼承Test類通過static產生實例的類名: ', get_class($arr1[1]), '<hr>';  // Test1
$arr2 = Test2::getIns();
echo 'Test2類繼承Test類通過self產生實例的類名: ', get_class($arr2[0]), '<br>';    // Test
echo 'Test2類繼承Test類通過static產生實例的類名: ', get_class($arr2[1]);          // Test2

通過以上代碼可知,當子類繼承父類的情況下,self與static有所不同: 

1、new self() 無論是子類還是父類誰調用,都指向被定義時它所在的類。

2、new static() 則由調用者決定,哪個類調用就指向哪個類。

 

總結:通過對比可知,new self() 與 new static() 區別在於是否繼承,如果沒胡繼承則二者效果相同,如果有繼承,則self仍指向被定義時的類,而static則指向調用者的類。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章