PHP 的 new static 和 new self

PHP 的 new static 和 new self

内容导读

收集整理的这篇技术教程文章主要介绍了PHP 的 new static 和 new self,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含999字,纯文字阅读大概需要2分钟

内容图文

下面我们举个栗子:
class Father {

public static function getSelf() {



return new self();

}

public static function getStatic() {



return new static();

}}class Son extends Father {}echo get_class(Son::getSelf()); // Fatherecho get_class(Son::getStatic()); // Sonecho get_class(Father::getSelf()); // Fatherecho get_class(Father::getStatic()); // Father

new self

这里面注意这一行 get_class(Son::getStatic()); 返回的是 Son 这个 class, 可以总结如下:

self 返回的是 new self 中关键字 new 所在的类中,比如这里例子的 :

public static function getSelf() {

return new self(); // new 关键字在 Father 这里}

始终返回 Father。

new static

static 则上面的基础上,更聪明一点点:static 会返回执行 new static() 的类,比如 Son 执行 get_class(Son::getStatic()) 返回的是 Son, Father 执行 get_class(Father::getStatic()) 返回的是 Father

而在没有继承的情况下,可以认为 new self 和 new static 是返回相同的结果。

以上就是PHP 的 new static 和 new self的详细内容。

内容总结

以上是为您收集整理的PHP 的 new static 和 new self全部内容,希望文章能够帮你解决PHP 的 new static 和 new self所遇到的程序开发问题。 如果觉得技术教程内容还不错,欢迎将网站推荐给程序员好友。

内容备注

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。


本文关键词:

联系我们

在线咨询:点击这里给我发消息

邮件:w420220301@qq.com