I saw in some frameworks this line of code:
return new static($view, $data);
how do you understand the new static
?
I saw in some frameworks this line of code:
return new static($view, $data);
how do you understand the new static
?
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
.
© 2022 - 2024 — McMap. All rights reserved.
decltype(*this)
with polymorphism disabled? What horrible keyword usage! – Kingwoodstatic
that was already reserved." php.net/manual/en/language.oop5.late-static-bindings.php – Timmonsstatic
is used or the current subclass of it, then yes. – Timmonsdecltype(*this)
. The polymorphism-disabled version would benew self
. – Efikdecltype
is already "polymorphism-disabled". As a static construct it seems to be likestatic
here to me.self
would be a version that employs RTTI. – Kingwooddecltype
myself so I was going on your earlier comment. "decltype(*this) with polymorphism disabled" implies that normally "decltype(*this)" is polymorphism-enabled. – Efik