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 self
和 new static
是返回相同的结果。
tips: 可以用一个好的 ide 来直接看注释。比如 phpstorm:
happy hacking
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
YII2框架中使用RBAC对模块,控制器,方法的权限控制及规则的使用示例
YII2框架中ActiveDataProvider与GridView的配合使用操作示例
PhpStorm的使用教程(本地运行PHP+远程开发+快捷键)
网友评论