下面例子中使用self
和static
有什么区别?
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
的 protected 静态属性。当您在 Foo
类中使用 self
来引用该属性时,您引用的是同一个类。
因此,如果您尝试在 Foo
类的其他地方使用 self::$bar
但您的 Bar
类具有不同的值对于该属性,它将使用 Foo::$bar
而不是 Bar::$bar
,这可能不是您想要的:
class Foo
{
protected static $bar = 1234;
}
class Bar extends Foo
{
protected static $bar = 4321;
}
当您通过 static
调用方法时,您正在调用一个名为 late static bindings 的功能。 (在 PHP 5.3 中引入)。
在上述场景中,使用 self
将导致 Foo::$bar
(1234)。
并且使用 static
将导致 Bar::$bar
(4321),因为使用 static
,解释器会考虑 中的重新声明>Bar
运行时的类。
// self
var_dump(Foo::$bar);
// (int) 1234
// static
var_dump(Bar::$bar);
// (int) 4321
您通常对方法甚至类本身使用后期静态绑定(bind),而不是属性,因为您不经常在子类中重新声明属性;可以在以下相关问题中找到使用 static
关键字调用后期绑定(bind)构造函数的示例:New self vs. new static
但是,这并不排除将 static
与属性一起使用。
关于php - PHP 中的 self::$bar 和 static::$bar 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11710099/