php的newstatic和self

今天了解了一下再类中使用new static 和new self.

class Foo
{
   public static function baz() {
      return new static();
   }
}

class Bar extends Foo
{
}

$wow = Bar::baz();  // $wow is now a `Bar`, even though `baz()` is in base `Foo`

class Foo
{
   public static function baz() {
      return new self();
   }
}

$x = Foo::baz();  // $x is now a `Foo`

总结两者的区别是new static返回的当前class的类;new self返回父class的类。

new static() - returns the object of current class, regardless of which classes is extended, and new self() - returns the object from the class in which that method was declared or extended(last version of the function)

--------EOF---------
微信分享/微信扫码阅读