深圳旅游公司网站,重庆哪家做网站,广州越秀区重点场所,wordpress 4.4.7浅谈PHP中new self()和new static()的区别#xfeff;本文介绍了PHP中new self()和new static()的区别#xff0c;分享给大家#xff0c;也给自己留个笔记。1.new static()是在PHP5.3版本中引入的新特性。2.无论是new static()还是new self()#xff0c;都是new了一个新的对…浅谈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()和new static()的区别就暂时说这么多希望对读者的理解有所帮助如果有不对的地方欢迎拍砖扔蛋。也希望大家多多支持码农之家。以上就是本次给大家分享的关于java的全部知识点内容总结大家还可以在下方相关文章里找到相关文章进一步学习感谢大家的阅读和支持。您可能感兴趣的文章: