在类之外声明一个新的静态变量


Declaring a new static variable outside of Class

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

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

如何做到这一点?

谢谢你的建议。

这是不可能的,因为静态变量,嗯。。。是STATIC,因此不能动态声明。

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

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');
当您访问对象的不存在属性时,会调用PHP中的

__get()魔术方法。

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

你可能有一个容器来处理这个问题

编辑:

请参阅:

PHP 中静态属性的Magic __get getter