4

有没有办法在该类之外声明新的静态变量,即使它没有在类中设置?

// Using this class as a static object.
Class someclass {
    // There is no definition for static variables.
}

// This can be initialized
Class classA {
    public function __construct() {
        // Some codes goes here
    }
}

/* Declaration */
// Notice that there is no static declaration for $classA in someclass
$class = 'classA'
someclass::$$class = new $class();

怎么做到呢?

谢谢你的建议。

4

2 回答 2

2

__get()当您访问对象的不存在属性时,会调用 PHP 中的魔术方法。

http://php.net/manual/en/language.oop5.magic.php

您可能有一个容器,您可以在其中处理此问题。

编辑:

看到这个:

用于 PHP 中静态属性的魔术 __get getter

于 2011-06-10T13:23:43.363 回答
2

这是无法做到的,因为静态变量,嗯……是静态的,因此不能动态声明。

编辑: 您可能想尝试使用注册表。

class Registry {

    /**
     * 
     * Array of instances
     * @var array
     */
    private static $instances = array();

    /**
     * 
     * Returns an instance of a given class.
     * @param string $class_name
     */
    public static function getInstance($class_name) {
        if(!isset(self::$instances[$class_name])) {
            self::$instances[$class_name] = new $class_name;
        }

        return self::$instances[$class_name];
    }

}

Registry::getInstance('YourClass');
于 2011-06-10T13:24:57.297 回答