Search code examples
phpdeclarationstatic-variables

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() {
        // 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.


Solution

  • 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');