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()); //Father
print get_class($sun1->getNewCaller()); //Sun1
print get_class($sun2->getNewFather()); //Father
print get_class($sun2->getNewCaller()); //Sun2

我们发现,无论是Sun1还是Sun2,调用getNewFather()返回的对象都是类Father的实例,而getNewCaller()则返回的是调用者的实例。

​​​​​​​由此可知:

new self() 在哪个类里便是new的哪个类

new static()哪个类调用他便是new的哪个类

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值