1

I see in Symphony in Symfony\Component\HttpFoundation\Request (line 1922) such construction

return new static($query, $request, $attributes, $cookies, $files, $server, $content);

I was not able to google it. What does it mean?

Thomas Rollet
  • 1,573
  • 4
  • 19
  • 33
Thelambofgoat
  • 609
  • 1
  • 11
  • 24

1 Answers1

3

From this answer

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.

Community
  • 1
  • 1
Domain
  • 11,562
  • 3
  • 23
  • 44