php 中 new self 和 new static区别

时间:2024-07-14 07:09:47

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

new self()

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

示例:

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”(延迟静态绑定)。

示例:

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() 更为适用。