5

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.

Valour
  • 773
  • 10
  • 32

2 Answers2

2

__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

Community
  • 1
  • 1
Tomasz Kowalczyk
  • 10,472
  • 6
  • 52
  • 68
  • This does not apply to static variables. A static variable is a property of a **CLASS**, not of an **OBJECT**. – cypher Jun 10 '11 at 13:25
  • So you are saying I cannot declare it even with a function inside of it? Example: `public static function set($class) { self::$$class = new $class(); }` – Valour Jun 10 '11 at 13:36
  • 1
    No, this applies only to class declaration, no way it can be done dynamically. Use static array property or so. – Tomasz Kowalczyk Jun 10 '11 at 13:39
2

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');
cypher
  • 6,822
  • 4
  • 31
  • 48
  • How about declaring them with a static function inside that class? like `public static function set($class) { self::$$class = new $class(); }` – Valour Jun 10 '11 at 13:32
  • 1
    This isn't about context, **static variables can NOT be declared at runtime.** If you try it this way, you'll stil get a fatal error. – cypher Jun 10 '11 at 13:38