您好,欢迎访问一九零五行业门户网

关于PHP new static 和 new self详解

使用 self:: 或者 __class__ 对当前类的静态引用,取决于定义当前方法所在的类:使用 static:: 不再被解析为定义当前方法所在的类,而是在实际运行时计算的。也可以称之为“静态绑定”,因为它可以用于(但不限于)静态方法的调用。
最近在一个视频的评论被问到一个小问题:这里选择用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:
以上就是本文的全部内容,希望对大家的学习有所帮助。
相关推荐:
php中new self()与new static()的区别分析
php中self与this的使用
php 中 this self static 的区别
以上就是关于php new static 和 new self详解的详细内容。
其它类似信息

推荐信息