3

What is the best way to get a global variable inside a class?

I know I can easily just use "global $tmpVar;" inside a class function but is there a way to global the variable so it is available for all functions in a class without needing the ugly global $tmpVar; inside each function?

Ideally right after the "class tmpClass() {" declaration would be great, but not sure if this is possible.

Joe
  • 3,043
  • 9
  • 43
  • 56
  • 1
    Related: http://stackoverflow.com/questions/1812472/in-a-php-project-how-do-you-organize-and-access-your-helper-objects – Pekka Oct 02 '10 at 09:25
  • Can you add some detail on what you are doing? Because global variables are often not the best/cleanest way to go anyway; alternative suggestions might come up – Pekka Oct 02 '10 at 09:26
  • 2
    That's not ideal, that's horrible. The best way (95% of the time) is not to use global variables at all. Be glad you have to use the "ugly" `global $var;`, it will make it marginally easier to understand WTF the code is doing soon enough. –  Oct 02 '10 at 09:29

1 Answers1

2

You can use Static class variables. These variables are not associated with a class instance, but with the class definition.

class myClass {
    public static $classGlobal = "Default Value" ;

    public function doStuff($inVar) {
        myClass::$classGlobal = $inVar ;
    }
}

echo myClass::$classGlobal."\n" ;
$instance = new myClass() ;
echo myClass::$classGlobal."\n" ;
$instance->doStuff("New Value") ;
echo myClass::$classGlobal."\n" ;

Output:

Default Value
Default Value
New Value
Gus
  • 7,289
  • 2
  • 26
  • 23