Dynamically populating a static variable in PHP
我有两个静态值:"type"和"typeid"。类型是人类可读的和常量,需要根据类型的值从数据库中查找typeid。当类定义首次加载时,我需要执行一次查找
举例来说,这里有一些代码不起作用,因为您不能在声明空间中调用函数。
1 2 3 4 | MyClass extends BaseClass { protected static $type ="communities"; protected static $typeID = MyClass::lookupTypeID(self::$type); } |
是否有一个在加载类定义时只调用一次的magic方法?如果有明显的东西,我会错过的。
不知羞耻地从PHP手册的静态关键字注释中提取:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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() ?> |
简单而无需任何魔力,不要忘记,您可以始终将变量定义为空,并测试它是否为空(仅在那时执行db调用)。那么,如果您希望在构建或包含类时发生这种情况,这只是一个问题(包括ou once等…)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | MyClass extends BaseClass { protected static $type ="communities"; protected static $typeID = null; public function __construct(){ if(is_null(self::$typeID)){ self::lookupTypeID(self::$type); } } public static lookupTypeID($type){ self::$typeID = //result of database query } } |
或
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | MyClass::lookupTypeID(); //call static function when class file is included (global space) MyClass extends BaseClass { protected static $type ="communities"; protected static $typeID = null; public function __construct(){ } public static lookupTypeID($type=null){ if(is_null($type)){ $type = self::$type; } self::$typeID = //result of database query (SELECT somefield FROM sometable WHERE type=$type) etc.. } } |
静态构造函数更像工厂方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | if(!function_exists(build_myclass)){ function build_myclass(){ return MyClass::build(); } } MyClass extends BaseClass { protected static $type ="communities"; protected static $typeID = null; public function __construct(){ } public static function build(){ return new self(); //goes to __construct(); } } $class = new MyClass(); //or $class = MyClass::build(); //or $class = build_myclass(); |
这种东西通常被称为"静态构造函数",但PHP缺少这种东西。您可能需要考虑在PHP手册注释中建议的解决方法之一,例如http://www.php.net/manual/en/language.oop5.static.php 95217