class Foo {
public static function foobar() {
self::whereami();
}
protected static function whereami() {
echo 'foo';
}
}
class Bar extends Foo {
protected static function whereami() {
echo 'bar';
}
}
Foo::foobar();
Bar::foobar();
预期结果 foobar
实际结果 foofoo
更糟糕的是,服务器仅限于 php 5.2
最佳答案
您只需要一言以蔽之!
问题在于你调用whereami()的方式,而不是self::你应该使用static::。所以类 Foo 应该是这样的:
class Foo {
public static function foobar() {
static::whereami();
}
protected static function whereami() {
echo 'foo';
}
}
换句话说,“静态”实际上使对 whereami() 的调用是动态的 :) - 这取决于调用所在的类。
关于php - 在 php 中扩展静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5853310/