Joe
Joe

Reputation: 3109

php - global variables inside all class functions

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.

Upvotes: 3

Views: 6635

Answers (1)

Gus
Gus

Reputation: 7349

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

Upvotes: 2

Related Questions