温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP中的new self和new static有什么区别

发布时间:2020-06-08 22:48:26 来源:亿速云 阅读:230 作者:Leah 栏目:编程语言

这篇文章给大家分享的是PHP中的new self和new static的区别。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

new static() 是在php5.3版本引入的新特性

new static 和 new self() 都是 new 一个对象

直接看代码

class Father
{
    public function getNewFather()
    {
        return new self();
    }
  
    public function getNewCaller()
    {
        return new static();
    }
}
  
$f = new Father();
  
var_dump(get_class($f->getNewFather())); // Father
var_dump(get_class($f->getNewCaller())); // Father

getNewFather和getNewCaller 都是返回的 Father 这个实列

到这里貌似 new self() 还是 new static() 是没有区别的

接着看下面的示例

class Sun1 extends Father{
  
}
  
$sun1 = new Sun1();
  
var_dump($sun1->getNewFather()); // object(Father)#4 (0) { }
var_dump($sun1->getNewCaller()); // object(Sun1)#4 (0) { }

getNewFather 返回的是Father的实列,

getNewCaller 返回的是调用者的实列

他们的区别只有在继承中才能体现出来、如果没有任何继承、那么二者没有任何区别

new self() 返回的实列是不会变的,无论谁去调用,都返回的一个类的实列,

new static则是由调用者决定的。

看完上述内容,你们对PHP中的new self和new static的区别大概了解了吗?如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI