What does the new static mean?

I saw in some frameworks this line of code:

return new static($view, $data); 

how do you understand new static ?

+46
php
Apr 09 '13 at 9:55 on
source share
1 answer

When you write new self() inside a member function of a class, you get an instance of that class. This is 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 Foo even if the static determinant you used was for the derived class:

 class Bar extends Foo { } $z = Bar::baz(); // $z is now a `Foo` 

If you want to enable polymorphism (in a sense), and PHP pays attention to the classifier you are using, you can change the self keyword for the static :

 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 function, known as late static binding ; do not confuse it for other, more common uses of the static .

+73
Apr 09 '13 at 10:05
source share



All Articles