gpt4 book ai didi

PHP的new static和new self的区别与使用

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 30 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章PHP的new static和new self的区别与使用由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

下面我们举个栗子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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()); // Father
echo get_class(Son::getStatic()); // Son
echo get_class(Father::getSelf()); // Father
echo get_class(Father::getStatic()); // Father

new self 。

这里面注意这一行 get_class(Son::getStatic()); 返回的是 Son 这个 class, 可以总结如下: self 返回的是 new self 中关键字 new 所在的类中,比如这里例子的 :

?
1
2
3
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 是返回相同的结果.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我.

原文链接:https://learnku.com/articles/31929 。

最后此篇关于PHP的new static和new self的区别与使用的文章就讲到这里了,如果你想了解更多关于PHP的new static和new self的区别与使用的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com