user10971950
user10971950

Reputation: 301

How to reference child class in inherited method?

Assuming the following:

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?
 }

}

Calling B::new(), it actually returns a new A --

How to get it to return a new B since B inherited that method?

Edit: There has been an accusation of duplicate question and my answer to that: it's not really a duplicate as the previously referenced question was about a change in language structure as opposed to this question which is about how inheritance works. They're very close and have the same answer but they're not the same question. It's like saying 2 * 2 is a duplicate of 2 + 2; they have the same numbers and end up with the same result but they're asking different questions.

Upvotes: 1

Views: 68

Answers (1)

Wiimm
Wiimm

Reputation: 3517

Replace new self() by new static() (late binding):

public static function new() 
{
    return new static();
}

Upvotes: 2

Related Questions