class A{
const FOO = 1;
}
class B extends A{
const FOO = 5;
function foo(){
print self::FOO;
print static::FOO;
}
}
$b = new B;
$b->foo();
在这两种情况下,它都会打印 5。
所以在常量上使用静态和自身没有区别吗?
在后期静态绑定的上下文中,存在差异。
请考虑以下代码:
<?php
class A {
const FOO = 1;
function bar() {
print self::FOO;
print "'n";
print static::FOO;
}
}
class B extends A {
const FOO = 5;
}
$b = new B;
$b->bar(); // 1 5
如果运行此代码,则输出将为:
1
5
当引用self::FOO
时,1
的值被打印出来(即使bar()
是在类B
上调用的,但是当使用static
关键字时,后期静态绑定生效,并且在使用static关键字时引用了B
而不是A
的FOO
常量。
这与 PHP 5.3 及更高版本相关。
在您的示例中,没有足够的内容来查看差异。但是,如果您有:
class Foo
{
protected static $FooBar = 'Foo';
public function FooBar()
{
echo "static::'$FooBar = " . static::$FooBar . PHP_EOL;
echo "self::'$FooBar = " . self::$FooBar . PHP_EOL;
}
}
class Bar extends Foo
{
protected static $FooBar = 'Bar';
}
$bar = new Bar();
$bar->FooBar();
你会看到差异(范围和正在解析的实例[继承与基础](
自我、父和静态关键字
是的,有区别。在示例代码中,self
和 static
都引用同一个const FOO
声明。
用户"drew010"发送的示例显示了差异。