问题描述
在下面的示例中,使用self
和static
有什么区别?
What is the difference between using self
and static
in the example below?
class Foo
{
protected static $bar = 1234;
public static function instance()
{
echo self::$bar;
echo "\n";
echo static::$bar;
}
}
Foo::instance();
产生
1234
1234
推荐答案
使用self
引用类成员时,即表示您在其中使用关键字的类.在这种情况下,您的Foo
类定义了一个受保护的静态属性,称为$bar
.当您在Foo
类中使用self
来引用该属性时,您所引用的是同一类.
When you use self
to refer to a class member, you're referring to the class within which you use the keyword. In this case, your Foo
class defines a protected static property called $bar
. When you use self
in the Foo
class to refer to the property, you're referencing the same class.
因此,如果您尝试在Foo
类中的其他位置使用self::$bar
,但是您有一个Bar
类,其属性值不同,则它将使用Foo::$bar
而不是Bar::$bar
,这可能不会就是你想要的:
Therefore if you tried to use self::$bar
elsewhere in your Foo
class but you had a Bar
class with a different value for the property, it would use Foo::$bar
instead of Bar::$bar
, which may not be what you intend:
class Foo
{
protected static $bar = 1234;
}
class Bar extends Foo
{
protected static $bar = 4321;
}
当您通过static
调用方法时,您正在调用名为后期静态绑定(在PHP 5.3中引入).
When you call a method via static
, you're invoking a feature called late static bindings (introduced in PHP 5.3).
在上述情况下,使用self
将导致Foo::$bar
(1234).使用static
会导致Bar::$bar
(4321),因为使用static
时,解释器会在运行时考虑Bar
类中的重新声明.
In the above scenario, using self
will result in Foo::$bar
(1234).And using static
will result in Bar::$bar
(4321) because with static
, the interpreter takes takes into account the redeclaration within the Bar
class during runtime.
您通常将后期静态绑定用于方法甚至类本身,而不是属性,因为您通常不会在子类中重新声明属性;可以在以下相关问题中找到使用static
关键字调用后期绑定的构造函数的示例:
You typically use late static bindings for methods or even the class itself, rather than properties, as you don't often redeclare properties in subclasses; an example of using the static
keyword for invoking a late-bound constructor can be found in this related question: New self vs. new static
但是,这并不排除将static
与属性一起使用.
However, that doesn't preclude using static
with properties as well.
这篇关于PHP中的self :: $ bar和static :: $ bar有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!