Declaring a new static variable outside of Class
Is there a way declaring new static variables outside of that class even if it's not set in 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开发者_Python百科() {
// Some codes goes here
}
}
/* Declaration */
// Notice that there is no static declaration for $classA in someclass
$class = 'classA'
someclass::$$class = new $class();
How can it be done?
Thank you for your advices.
This can't be done, because static variables, well... are STATIC and therefore cannot be declared dynamically.
EDIT: You might want to try using a registry.
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');
__get()
magic method in PHP is called when you access non-existent property of an object.
http://php.net/manual/en/language.oop5.magic.php
You may have a container within which you'll handle this.
Edit:
See this:
Magic __get getter for static properties in PHP
精彩评论