在PHP中动态填充静态变量

时间:2011-05-16 22:46:52

标签: php object static

我有两个静态值:“type”和“typeID”。 Type是人类可读且常量的,需要根据type的值从数据库中查找typeID。首次加载类定义时,我需要进行一次查找

为了说明,这里有一些代码不起作用,因为你不能在声明空间中调用函数。

MyClass extends BaseClass {
  protected static $type = "communities";
  protected static $typeID = MyClass::lookupTypeID(self::$type);
}

加载类定义时是否有一个魔术方法只调用一次?如果有明显的东西我就会错过它。

3 个答案:

答案 0 :(得分: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()
?>

答案 1 :(得分:3)

简单且无需魔法,不要忘记你总是可以将变量定义为null并测试它是否为null(仅在此时执行db调用)。那么,如果您希望在构建或包含类时发生这种情况(include_once等...),那么这只是一个问题。

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
    }
}

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..
    }
}

静态构造函数更像是工厂方法

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();

答案 2 :(得分:1)

这种东西通常被称为“静态构造函数”,但PHP缺乏这样的东西。您可能需要考虑PHP手册注释中建议的解决方法之一,例如http://www.php.net/manual/en/language.oop5.static.php#95217