Php - global variables inside all class functions

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

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

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

+3
source share
1 answer

You can use the variables of the Static class. These variables are not associated with an instance of a class, but with a 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" ;

Conclusion:

Default Value
Default Value
New Value
+2
source

Source: https://habr.com/ru/post/1767649/


All Articles