what means new static?

I saw in some frameworks this line of code:

return new static($view, $data);

how do you understand the new static?

34535 次浏览

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.