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.

3
  • 1
    Related: stackoverflow.com/questions/1812472/… Commented Oct 2, 2010 at 9: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 Commented Oct 2, 2010 at 9: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. Commented Oct 2, 2010 at 9:29

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.