php -- new self() 和 new static

看一段摘自网上的代码spa

class A {
  public static function get_self() {
    return new self();
  }
 
  public static function get_static() {
    return new static();
  }
}
 
class B extends A {}
 
echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_static()); // A

 

通俗点讲就是:code

new self();   在哪一个类里面执行的该代码,返回的就是哪一个类的对象。若是该代码只写在父类中,即便子类继承自父类,返回的依然是父类的对象。对象

new static();  哪一个类调用的它,返回的就是哪一个类的的对象。blog

相关文章
相关标签/搜索