new static和new self的区别
例1
class Father {
public function getSelf() {
return new self();
}
public function getStatic() {
return new static();
}
}
$f = new Father();
echo get_class($f->getSelf());
echo get_class($f->getStatic());
结果是Father Father
例2
class Son1 extends Father {
}
class Son2 extends Father {
}
$son1 = new Son1();
$son2 = new Son2();
echo get_class($son1->getSelf());
echo get_class($son1->getStatic());
echo get_class($son2->getSelf());
echo get_class($son2->getStatic());
结果是Father Son1 Father Son2
[注] get_class()方法是用于获取实例所属的类名.
new self() 和new static()和new 类名()都是用来实例化对象的.
从上面的对比:
1.他们的区别只有在继承中才能体现出来,如果没有任何继承,那么这两者是没有区别的,实例化的都是所在类的对象.
2.在出现继承的时候,new self()返回的实例是万年不变的,无论谁去调用,都返回同一个类(即所在类)的实例,而new static()则是由调用者决定的。