Declaring a new static variable outside the class

Is there a way that declares new static variables outside this class, even if it is not defined in the 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(); 

How can I do that?

Thanks for your advice.

+4
source share
2 answers

This is not possible because static variables, well ... are STATIC and therefore cannot be declared dynamically.

EDIT: You might want to try using the 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'); 
+2
source

__get() magic method in PHP is called when accessing an object that does not exist.

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

You may have a container in which you will handle this.

Edit:

See this:

__Get getter magic for static properties in PHP

+2
source

All Articles