在 PHP 中动态填充静态变量 [英] Dynamically populating a static variable in PHP
问题描述
我有两个静态值:type"和typeID".Type 是人类可读的和常量,typeID 需要根据 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.
推荐答案
无耻地从php手册的静态关键字注释中拉取:
shamelessly pulled from the php manual's static keyword comments:
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()
?>
这篇关于在 PHP 中动态填充静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!