PHP中new self()和new static()的区别探究

1.new static()是在PHP5.3版本中引入的新特性。spa

2.不管是new static()仍是new self(),都是new了一个新的对象。code

3.这两个方法new出来的对象有什么区别呢,说白了就是new出来的究竟是同一个类实例仍是不一样的类实例呢?对象

为了探究上面的问题,咱们先上一段简单的代码:blog

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这个类的实例。get

打印的结果为:FatherFatherio

到这里,貌似new self()和new static()是没有区别的。咱们接着往下走:function

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的,因此子类继承了这两个方法。class

打印的结果是: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()的区别就暂时说这么多,但愿对读者的理解有所帮助,若是有不对的地方欢迎拍砖扔蛋。

相关文章
相关标签/搜索