php中有很多函数我们分不清,比如说new self()和new static()有什么区别?打击可能不能完全解释出来,当然也有很厉害的小伙伴,那本文就和大家分享一下php中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();
print get_class($f->getnewfather());
print get_class($f->getnewcaller());
注意,上面的代码get_class()方法是用于获取实例所属的类名。
这里的结果是:无论调用getnewfather()还是调用getnewcaller()返回的都是father这个类的实例。
打印的结果为:fatherfather
到这里,貌似new self()和new static()是没有区别的。我们接着往下走:
class sun1 extends father {
}
class sun2 extends father {
}
$sun1 = new sun1();
$sun2 = new sun2();
print get_class($sun1->getnewfather());
print get_class($sun1->getnewcaller());
print get_class($sun2->getnewfather());
print get_class($sun2->getnewcaller());
看上面的代码,现在这个father类有两个子类,由于father类的getnewfather()和getnewcaller()是public的,所以子类继承了这两个方法。
打印的结果是:fathersun1fathersun2
我们发现,无论是sun1还是sun2,调用getnewfather()返回的对象都是类father的实例,而getnewcaller()则返回的是调用者的实例。
即$sun1返回的是sun1这个类的实例,$sun2返回的是sun2这个类的实例。
现在好像有点明白new self()和new static()的区别了。
首先,他们的区别只有在继承中才能体现出来,如果没有任何继承,那么这两者是没有区别的。
然后,new self()返回的实例是万年不变的,无论谁去调用,都返回同一个类的实例,而new static()则是由调用者决定的。
上面的$sun1->getnewcaller()的调用者是$sun1对吧!$sun1是类sun1的实例,所以返回的是sun1这个类的实例,$sun2同样的道理就不赘述了。
相关推荐:
php中new self()详解_php教程
new static() 和 new self() 的区别异同,staticself
new static()是做什么用的?该如何处理
以上就是new self()和new static()有什么区别的详细内容。