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();开发者_Python百科
Which displays:
Foo<br />Foo
When it should display:
Bar<br />Foobar
Any way this could be done?
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:
$table = array ('classname' => 'tablename', 'secondClassname' => 'secondTablename');
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.
精彩评论