对比 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>‘; // Testecho ‘Test1类继承Test类通过static产生实例的类名: ‘, get_class($arr1[1]), ‘<hr>‘; // Test1$arr2 = Test2::getIns();echo ‘Test2类继承Test类通过self产生实例的类名: ‘, get_class($arr2[0]), ‘<br>‘; // Testecho ‘Test2类继承Test类通过static产生实例的类名: ‘, get_class($arr2[1]); // Test2

通过以上代码可知,当子类继承父类的情况下,self与static有所不同: 

1、new self() 无论是子类还是父类谁调用,都指向被定义时它所在的类。

2、new static() 则由调用者决定,哪个类调用就指向哪个类。

总结:通过对比可知,new self() 与 new static() 区别在于是否继承,如果没胡继承则二者效果相同,如果有继承,则self仍指向被定义时的类,而static则指向调用者的类。

相关文章