如何在继承的方法中引用子类?

假设以下内容:


class A

{

    public static function new() 

    {

       return new self();

     }

}


class B extends A

{


}



class C 

{

  public function main() 

 {

   $b = B::new(); // it actually returns a new A -- how to get it to return a new B since B inherited that method?

 }


}

呼叫B::new(),实际上会传回新的A-


由于B继承了该方法,如何获取它以返回新的B?



慕工程0101907
浏览 109回答 1
1回答

守着一只汪

替换new self()为new static()(后期绑定):public static function new() {    return new static();}
打开App,查看更多内容
随时随地看视频慕课网APP