我正在使用这个系统:
abstract class Model {
static $table = "";
abstract static function init();
public static function getById() {
$table = self::$table;
}
}
class Model_user extends Model {
static function init() {
self::$table = "users";
}
}
class Model_post extends Model {
static function init() { self::$table = "post"; }
}
// ...
Model_user::init();
Model_post::init();
$user = Model_user::getById(10);
$post = Model_user::getById(40);
我希望它是这样的,因此每个子类都有自己的一组静态成员,可以通过Model中的静态函数访问它们。我不能使用static ::关键字,因为我必须使用PHP 5.2.16。不幸的是,由于以下示例中显示的PHP问题,我不能只说“self ::”:
class Foo {
static $name = "Foo";
static function printName() {
echo self::$name;
}
}
class Bar extends Foo {
static $name = "Bar";
}
class Foobar extends Foo {
static $name = "Foobar";
}
Bar::printName();
echo "<br />";
Foobar::printName();
显示:
Foo<br />Foo
何时显示:
Bar<br />Foobar
任何方式都可以做到这一点?
答案 0 :(得分:1)
看来你无法访问父类静态方法代码中的子类静态成员。已在this comment on the php documentation about the static keyword中发布了一个解决方案。解决方案是使您的表变量成为此形式的数组:
$table = array ('classname' => 'tablename', 'secondClassname' => 'secondTablename');
答案 1 :(得分:0)
静态的一切都属于类,而不属于对象。因此,静态方法不会从父类继承,只会访问它们所定义的类中的成员。
在Java中,这种静态方法调用(Foobar::printName()
)甚至会引发错误。