php 中 new self() 和 new static()区别

在 PHP 中,new self()new static() 都用于创建当前类的实例,但它们在运行时绑定和继承上下文中的行为有所不同。

new self()

self 关键字引用的是当前类本身。无论在哪个类中调用它,它总是引用定义关键字的那个类。这意味着,如果你在父类的一个方法中使用 new self(),那么即使在子类中调用这个方法,它仍然会创建父类的实例,而不是子类的实例。

示例:

php 复制代码
class ParentClass {
    public function createInstance() {
        return new self();
    }
}

class ChildClass extends ParentClass {}

$child = new ChildClass();
$instance = $child->createInstance(); // 这将创建 ParentClass 的实例

new static()

static 关键字则不同,它引用的是调用该方法的类。这意味着如果你在父类的方法中使用 new static(),并且这个方法在子类中被调用,那么它将创建子类的实例,而不是父类的实例。这是 PHP 中的"late static binding"(延迟静态绑定)。

示例:

php 复制代码
class ParentClass {
    public function createInstance() {
        return new static();
    }
}

class ChildClass extends ParentClass {}

$child = new ChildClass();
$instance = $child->createInstance(); // 这将创建 ChildClass 的实例

总结:

  • new self() 总是创建当前类的实例,不管调用它的对象是什么。
  • new static() 创建调用该方法的类的实例,允许更灵活的继承和多态性。

因此,在需要根据调用上下文动态确定实例类型的情况下,new static() 是更合适的选择。而在需要确保总是创建某个特定类的实例时,new self() 更为适用。

相关推荐
凤山老林1 小时前
04-Java JDK, JRE和JVM
java·开发语言·jvm
小成202303202657 小时前
Linux高级02
linux·开发语言
薿夜7 小时前
SpringSecurity(三)
android
知行合一。。。7 小时前
Python--04--数据容器(总结)
开发语言·python
咸鱼2.07 小时前
【java入门到放弃】需要背诵
java·开发语言
ZK_H7 小时前
嵌入式c语言——关键字其6
c语言·开发语言·计算机网络·面试·职场和发展
A.A呐7 小时前
【C++第二十九章】IO流
开发语言·c++
椰猫子7 小时前
Java:异常(exception)
java·开发语言
lifewange7 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
cmpxr_8 小时前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法