Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


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...

like image 497
atomicharri Avatar asked Feb 06 '09 04:02

atomicharri


People also ask

Is a global variable is accessible to all the methods in the class?

Global variables are not technically allowed in Java. A global variable is one declared at the start of the code and is accessible to all parts of the program. Since Java is object-oriented, everything is part of a class. ... A static variable can be declared, which can be available to all instances of a class.

Are global variables accessible in functions?

Global Variables This means that a global variable can be accessed inside or outside of the function.


1 Answers

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

<?php
    // 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() {
            print_r($this->{_SYSTEM_});
        }

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

    }

    $foo = new Foo;
    $foo->bar();

?>
like image 197
frglps Avatar answered Nov 06 '22 13:11

frglps