WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question

closed as off topic by kaiser, Chip Bennett, toscho Apr 7 '12 at 20:46

Questions on WordPress Development Stack Exchange are expected to relate to WordPress within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

This is technically not a WordPress question, IMO. – John P Bloch Jun 19 '11 at 15:08

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:

global $x;

is the same as


I personally would use a static variable in your function:

function my_data(){
  static $data = null;
  if(null === $data)
    $data = new MY_Class();
  return $data;

Then anywhere in your code, you could just write $vars = my_data(); and have the one instantiation of your class.

Hope that helped!

share|improve this answer
Thanks, John! When I use global $x; $x->var ... in other functions, it doesn't work. instead, I have to use $v=my_data(), then, the $v->var works. – Jenny Jun 19 '11 at 23:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.