Making a global variable accessible for every function inside a class


Question

I have a variable on the global scope that is named ${SYSTEM}, where SYSTEM is a defined constant. I've got a lot of classes with functions that need to have access to this variable and I'm finding it annoying declaring global ${SYSTEM}; every single time.

I tried declaring a class variable: public ${SYSTEM} = $GLOBALS[SYSTEM]; but this results in a syntax error which is weird because I have another class that declares class variables in this manner and seems to work fine. The only thing I can think of is that the constant isn't being recognised.

I have managed to pull this off with a constructor but I'm looking for a simpler solution before resorting to that.


EDIT The global ${SYSTEM} variable is an array with a lot of other child arrays in it. Unfortunately there doesn't seem to be a way to get around using a constructor...

1
13
7/24/2011 7:17:04 PM

This is how I access things globally without global.

class exampleGetInstance 
{

private static $instance;

public $value1;
public $value2;


private function initialize() 
{
    $this->value1 = 'test value';
    $this->value2 = 'test value2';

}

public function getInstance()
{
    if (!isset(self::$instance))
    {
        $class = __CLASS__;
        self::$instance = new $class();
        self::$instance->initialize();
    }
    return self::$instance;
}

}

$myInstance = exampleGetInstance::getInstance();

echo $myInstance->value1;

$myInstance is now a reference to the instance of exampleGetInstance class.

Fixed formatting

8
2/15/2012 4:35:16 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon