PHP:具有静态成员的类层次结构
我正在开发这个系统:
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);
我希望每个子类都有自己的一组静态成员,这些成员可以通过模型中的静态函数访问。我无法使用 static:: 关键字,因为我必须使用 PHP 5.2.16。不幸的是,我不能只说“self::”,因为下面的示例中揭示了 PHP 的问题:
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
有什么办法可以做到这一点吗?
I have this system which I'm working on:
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);
I want it to be so each subclass has its own set of static members which can be accessed by the static functions in Model. I can't use the static:: keyword because I have to use PHP 5.2.16. Unfortunately, I can't just say "self::" because of a problem with PHP revealed in the below example:
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();
Which displays:
Foo<br />Foo
When it should display:
Bar<br />Foobar
Any way this could be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所有静态的东西都属于类,而不是对象。因此静态方法不是从父类继承的,只会访问定义它们的类内部的成员。
在 Java 中,这种静态方法调用 (
Foobar::printName()
) 甚至会抛出一个错误。Everything that is static belongs to the class, not to an object. Therefore static methods are not inherited from a parent class and will only access members inside the class they are defined in.
In Java this sort of static method call (
Foobar::printName()
) would even throw an error.看来您无法在父类的静态方法的代码中访问子类的静态成员。解决方案已发布在 有关静态的 php 文档的此评论中关键字。解决方案是将表变量设置为以下形式的数组:
It seems you cannot access the children classes static members in the parent's static method's code. A solution has been posted in this comment on the php documentation about the static keyword. The solution would be to make your table variable an array of this form: