【发布时间】:2020-11-09 17:15:46
【问题描述】:
这是我的问题:
我想在每个子项中为静态变量设置不同的值(我不想实例化该类):
abstract class Model {
protected static $table;
static function setTable(){
if(!static::$table){
// ClassName in plural to match to the table Name
static::$table = strtolower(static::class . 's');
}
return static::$table;
}
}
class Service extends Model {
}
class Categorie extends Model {
}
class Information extends Model {
static $table = 'infos'; // Overrides ClassName + s
}
现在我想为每个孩子调用 setTable() 而不使用 new :
Service::setTable(); // Return "services"
Categorie::setTable(); // Return "services"
Information::setTable(); // Return "infos"
Categorie::setTable(); //Return "servicies"
事实上,真正的兴趣在于为每个表创建类,而不考虑我需要访问哪个表。
有什么想法吗? 如果您对如何“清除静态缓存”有任何想法,这也可能是一个解决方案......
【问题讨论】:
-
这些类没有任何关系。你错过了扩展它们吗?
-
对不起,为了更简单,我重新编写了代码,我写问题时忘记扩展它们......
-
请复制/粘贴真实代码并删除任何不相关的内容。您发布的代码不会给出您发布的结果。 Here's a demo
-
我只是将您的代码复制到 phpfiddle 中,对所有类使用静态,并且 print_r 所有输出都可以。你的问题在哪里? example
-
@SimoneRossaini - 这不是他们的代码。您添加了他们的代码中缺少的东西。他们似乎想在某些情况下使用类名
标签: php class variables static