what means new static?

Php

Php Problem Overview


I saw in some frameworks this line of code:

return new static($view, $data);

how do you understand the new static?

Php Solutions


Solution 1 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHelloView Question on Stackoverflow
Solution 1 - PhpLightness Races in OrbitView Answer on Stackoverflow