当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP new static 和 new self详解

PHP new static 和 new self详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

2014133,九江入海,军海羊癫疯

最近在一个视频的评论被问到一个小问题:这里选择用static 而不是self有特殊的考虑么?或者我们可以这样转换一下问题:

php 的 new static 和 new self 具体有什么?

其实这个来看一个例子应该就很清晰了:

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

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

new self

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

public static function getself() {
  return new self(); // new 关键字在 father 这里
 }

始终返回 father

new static

2.static 则上面的基础上,更聪明一点点:static 会返回执行 new static() 的类,比如 son 执行 get_class(son::getstatic()) 返回的是 son, father 执行 get_class(father::getstatic()) 返回的是 father

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

tips: 可以用一个好的 ide 来直接看注释。比如 phpstorm:

happy hacking

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网