73
votes

I saw in some frameworks this line of code:

return new static($view, $data);

how do you understand the new static?

1
What framework was this? - Aleks G
for example laravel, but i found that only in the core, not while using their api - Hello
Check this page for more info; stackoverflow.com/questions/5197300/new-self-vs-new-static - user1467267
@Allendar: So it's like decltype(*this) with polymorphism disabled? What horrible keyword usage! - Lightness Races in Orbit

1 Answers

123
votes

When you write new self() inside a class's member function, you get an instance of that class. That's the magic of the self keyword.

So:

class Foo
{
   public static function baz() {
      return new self();
   }
}

$x = Foo::baz();  // $x is now a `Foo`

You get a Foo even if the static qualifier you used was for a derived class:

class Bar extends Foo
{
}

$z = Bar::baz();  // $z is now a `Foo`

If you want to enable polymorphism (in a sense), and have PHP take notice of the qualifier you used, you can swap the self keyword for the static keyword:

class Foo
{
   public static function baz() {
      return new static();
   }
}

class Bar extends Foo
{
}

$wow = Bar::baz();  // $wow is now a `Bar`, even though `baz()` is in base `Foo`

This is made possible by the PHP feature known as late static binding; don't confuse it for other, more conventional uses of the keyword static.