1

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.

user10971950
  • 301
  • 2
  • 8
  • Possible duplicate of [New self vs. new static](https://stackoverflow.com/questions/5197300/new-self-vs-new-static) – Progman Apr 27 '19 at 10:52
  • @Progman, 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. Edit: Just realized this comment might be perceived as snarky, it's not, I'm just offering my opinion! :) – user10971950 Apr 27 '19 at 16:06

1 Answers1

2

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

public static function new() 
{
    return new static();
}
Wiimm
  • 2,971
  • 1
  • 15
  • 25
  • Thank you, that worked! I wouldn't have ever found that out (and I've been developed PHP for 10 years lol, just never had to use static inheritance). – user10971950 Apr 27 '19 at 16:14