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
1. 这里无论是getNewFather还是getNewCaller都是返回的 Father 这个实列
2. 到这里貌似 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则是由调用者决定的。
发表回复