什么是新的静态? [英] what means new static?
问题描述
我在某些框架中看到了以下代码行:
I saw in some frameworks this line of code:
return new static($view, $data);
您如何理解new static
?
推荐答案
在类的成员函数中编写new self()
时,将获得该类的实例. 这就是self
关键字的魔力.
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.
所以:
class Foo
{
public static function baz() {
return new self();
}
}
$x = Foo::baz(); // $x is now a `Foo`
即使您使用的静态限定词用于派生类,您也会得到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`
(在某种意义上)如果要启用多态性,并且让PHP注意到您使用的限定符,则可以将self
关键字替换为static
关键字:
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`
这可以通过称为 后期静态绑定 ;请勿将其与关键字static
的其他更常规用法混淆.
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
.
这篇关于什么是新的静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!