new static() 和 new self() 在 PHP 中具有相同的功能。
它们都是用来在类中创建新实例的。区别在于:- new static() 使用类本身,在 static 上下文中解析。- new self() 使用调用对象的类。示例:<?php class A { public static function doStuff() { return new static(); } } class B extends A { } $a = A::doStuff(); echo get_class($a); // A $b = B::doStuff(); echo get_class($b); // B上面的例子中:- A::doStuff() 使用了 new static(),所以返回的是 A 的实例。- B::doStuff() 由于 B 继承自 A,所以静态方法 doStuff 的上下文仍然是 B,所以 new static() 实际上返回的是 B 的实例。
<?php class C { public function doStuff() { return new self(); } } class D extends C { } $c = (new C)->doStuff(); echo get_class($c); // C $d = (new D)->doStuff(); echo get_class($d); // C在上面的例子中:- (new C)->doStuff() 使用了 new self() ,所以返回的是 C 的实例。- (new D)->doStuff() 由于调用对象是 D 的实例,所以 new self() 实际上返回的是 D 的实例。总的来说:- new static() 始终会返回当前类的实例。- new self() 会返回调用当前方法的对象的类的实例。
网友回复