我有两个静态值:"type"和"typeID".Type是人类可读且常量的,需要根据type的值从数据库中查找typeID.首次加载类定义时,我需要进行一次查找
为了说明,这里有一些代码不起作用,因为你不能在声明空间中调用函数.
MyClass extends BaseClass {
protected static $type = "communities";
protected static $typeID = MyClass::lookupTypeID(self::$type);
}
Run Code Online (Sandbox Code Playgroud)
加载类定义时是否有一个神奇的方法被调用一次?如果有明显的东西我会错过它.
nat*_*lez 11
无耻地从php手册的静态关键字评论中提取:
Because php does not have a static constructor and you may want to initialize static class vars, there is one easy way, just call your own function directly after the class definition.
for example.
<?php
function Demonstration()
{
return 'This is the result of demonstration()';
}
class MyStaticClass
{
//public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
public static $MyStaticVar = null;
public static function MyStaticInit()
{
//this is the static constructor
//because in a function, everything is allowed, including initializing using other functions
self::$MyStaticVar = Demonstration();
}
} MyStaticClass::MyStaticInit(); //Call the static constructor
echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>
Run Code Online (Sandbox Code Playgroud)