在 PHP 中动态填充静态变量
我有两个静态值:“type”和“typeID”。类型是人类可读的且恒定的,并且需要根据类型的值从数据库中查找类型ID。我需要在首次加载类定义时进行一次查找。
为了说明这一点,这里有一些代码不起作用,因为您无法在声明空间中调用函数。
MyClass extends BaseClass {
protected static $type = "communities";
protected static $typeID = MyClass::lookupTypeID(self::$type);
}
是否有一个魔术方法在加载类定义时只调用一次?如果有什么明显的东西我会错过它。
I have two static values: "type" and "typeID". Type is human readable and constant, and typeID needs to be looked up from the database, based on the value of type. I need the lookup to happen once, when the class definition is first loaded
To illustrate, here is some code that doesn't work because you can't call functions in the declaration space.
MyClass extends BaseClass {
protected static $type = "communities";
protected static $typeID = MyClass::lookupTypeID(self::$type);
}
Is there a magic method that is called exactly once when the class definition is loaded? If there is something obvious I'm missing it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无耻地从php手册的静态关键字注释中提取:
shamelessly pulled from the php manual's static keyword comments:
简单且不需要魔法,不要忘记您始终可以将变量定义为 null 并测试它是否为 null(然后才进行 db 调用)。那么,如果您希望在构造或包含类时发生这种情况(include_once 等...)
,或者
静态构造函数更像是工厂方法,那么这只是一个问题
Simple and no magic needed, don't forget you can always define a variable as null and test that it is null (doing the db call only then). Then it's just a matter if you want that to happen when the class is constructed or included (include_once etc...)
or
a static constructor is more like a factory method
这样的东西通常被称为“静态构造函数”,但 PHP 缺少这样的东西。您可能需要考虑 PHP 手册注释中建议的解决方法之一,例如 http://www.php.net/manual/en/language.oop5.static.php#95217
Such a thing would normally be called a "static constructor", but PHP lacks such things. You might want to consider one of the workarounds suggested in the PHP manual comments, e.g. http://www.php.net/manual/en/language.oop5.static.php#95217