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
答案 0 :(得分:4)
您只需要单词更改!
问题在于你调用 whereami()的方式,而不是 self :: 你应该使用 static :: 。所以类 Foo 应如下所示:
class Foo {
public static function foobar() {
static::whereami();
}
protected static function whereami() {
echo 'foo';
}
}
换句话说,'静态'实际上调用 whereami()动态:) - 这取决于调用所在的类。
答案 1 :(得分:0)
答案 2 :(得分:0)
您是否也必须覆盖父函数foobar()?
class Foo {
public static function foobar() {
self::whereami();
}
protected static function whereami() {
echo 'foo';
}
}
class Bar extends Foo {
public static function foobar() {
self::whereami();
}
protected static function whereami() {
echo 'bar';
}
}
Foo::foobar();
Bar::foobar();
答案 3 :(得分:0)
尝试使用单例模式:
<?php
class Foo {
private static $_Instance = null;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if(self::$_Instance == null) {
self::$_Instance = new self();
}
return self::$_Instance;
}
public function foobar() {
$this->whereami();
}
protected function whereami() {
print_r('foo');
}
}
class Bar extends Foo {
private static $_Instance = null;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if(self::$_Instance == null) {
self::$_Instance = new self();
}
return self::$_Instance;
}
protected function whereami() {
echo 'bar';
}
}
Foo::getInstance()->foobar();
Bar::getInstance()->foobar();
?>