Php – Making a global variable accessible for every function inside a class


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.

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…

Best Solution

Ok, hopefully I've got the gist of what you're trying to achieve

    // the global array you want to access
    $GLOBALS['uname'] = array('kernel-name' => 'Linux', 'kernel-release' => '2.6.27-11-generic', 'machine' => 'i686');

    // the defined constant used to reference the global var
    define(_SYSTEM_, 'uname');

    class Foo {

        // a method where you'd liked to access the global var  
        public function bar() {

        // the magic happens here using php5 overloading
        public function __get($d) {
            return $GLOBALS[$d];  


    $foo = new Foo;