I have a Class with a lot of variables.
To get a variable, I have to write this line in each function:
$x = new MY_Class();
I guess there has to be another way?
I tried:
function my_data(){
global $x;
$x = new MY_Class();
return apply_filters( 'my_data', $x )
}
Then, I tried to use $x->var
in other functions that need the variables, but it doesn’t work.
How can I make the global $x
and its variables accessable by other functions? Thanks!
The way you’ve done it above should work. Once a variable is declared in global scope, it should be globally available (of course, your functions still need to declare it as a global:
global $x;
). You could also use the$GLOBALS
superglobal variable:is the same as
I personally would use a static variable in your function:
Then anywhere in your code, you could just write
$vars = my_data();
and have the one instantiation of your class.Hope that helped!