我正在从事一个项目,我希望能够在抽象基类中声明一个静态成员变量。我有一个 Model 类,一个中间 Post 类,最后是一个特定于站点的 Post 类,如下所示:
abstract class Model {
protected static $_table = null;
protected static $_database = null;
...
}
abstract class PostModel extends Model {
public function __construct() {
if ( !isset(self::$_table) ) {
self::$_table = 'some_table';
}
parent::__construct();
}
...
}
class SitePostModel extends PostModel {
public function __construct() {
if ( !isset(self::$_database) ) {
self::$_database = 'some_database';
}
parent::__construct();
}
...
}
我想从 Model 类中明确指出 $_table 和 $_database 成员是必需的。但是,从 PostModel 类的角度来看,$_table 确实是静态的,而从 SitePostModel 类的角度来看,$_database 确实是静态的。
这是实现我的目标的合法方式吗?在模型本身中声明静态变量是否意味着它们对于抽象基类只应存在一次,或者对于实际实例化类只应存在一次?
最佳答案
Is this a legitimate way to accomplish my goal?
没有。它不起作用,因此未通过基本的合法性测试。
Does declaring the static variables in the Model itself imply that they should exist only once for the abstract base class, or only once for the actual instantiated class?
静态变量是全局的,它们只存在一次。在您的情况下,每个类名。如果你有三个类名,你就会有三个(全局)变量。 protected 关键字仅控制三个静态变量的可见性/范围:
<?php
class A {
protected static $v = 'red';
public static function get() { return self::$v . ' - ' . static::$v;}
}
class B extends A {
protected static $v = 'blue';
}
class C extends B {
protected static $v = 'green';
}
echo C::get(); # red - green
关于抽象类中的 PHP 静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7798022/