我在PHP中有以下代码5.6.2。它有Father
、Guy extends Father
和Child extends Guy
类。所有这些类都有一个静态方法hi
,它输出类的名称:
class Father {
static function hi() {
echo "Father" . PHP_EOL;
}
}
class Guy extends Father {
static function hi() {
echo "Guy" . PHP_EOL;
}
static function test() {
self::hi();
static::hi();
parent::hi();
$anon = function() {
self::hi(); // shouldn't this call Guy::hi()?
static::hi();
parent::hi(); // shouldn't this call Father::hi()?
};
$anon();
}
}
class Child extends Guy {
static function hi() {
echo "Child" . PHP_EOL;
}
}
Child::test();
我期望的输出是:
Guy
Child
Father
Guy
Child
Father
前三行如预期。但最后三个令人惊讶的是:
Child //shouldn't this call Guy::hi()?
Child
Father //shouldn't this call Father::hi()?
因此,匿名函数$anon
似乎具有Child
的作用域。但是,它不应该与调用它的方法(即Guy
)具有相同的作用域吗?
第1版:此外,规范是否要求它像我预期的那样工作:
在实例或静态方法中定义的匿名函数将其作用域设置为在其中定义的类。否则,匿名函数将不受作用域限制。
EDIT 2:请注意,当我从
Guy::test()
中删除static
修饰符并像(new Child)->test();
一样调用它时,输出是预期的。第3版:在预料到一些更奇怪的行为后,我认为这是PHP->中的一个实际错误,根据错误报告
Child继承了函数test(),所以匿名函数的作用域是Child,也就是"它在其中定义的类"。