php -- new self() 和 new static

看一段摘自网上的代码

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

 

通俗点讲就是:

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

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

 

posted @ 2017-07-27 16:22  goodup  阅读(719)  评论(0编辑  收藏  举报

如有不对之处,欢迎指出,一起成长