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
关于 new self
需特别注意这一行代码 get_class(Son::getStatic()) 的输出结果为 Son。总结如下: self 关键字指向的是定义该方法的那个类,即示例中的 Father 类:
public static function getSelf() {
return new self(); // new 关键字在 Father 这里
}
无论何时调用,均固定返回 Father。
关于 new static
相比之下,static 机制更为智能:它会根据实际调用上下文决定返回类型。例如,当由 Son 类调用时,get_class(Son::getStatic()) 返回 Son;而当由 Father 类直接调用时,get_class(Father::getStatic()) 则返回 Father。
若不存在继承关系,new self 与 new static 的效果相同,均返回当前类。
以上内容涵盖了核心知识点,希望能对您的学习有所帮助,欢迎继续支持本站。