views:

21

answers:

1

I've got a plugin that is declared and hooked following best practices described in this related question:

http://stackoverflow.com/questions/1615118/wordpress-accessing-a-plugins-function-from-a-theme

So it looks (platonically) like this:

if ( !class_exists( 'Foo' ) ) {
  class Foo {
    ...
    public function do_stuff() {
      // does stuff
    }
  }
}

if ( class_exists( 'Foo' ) ) {
  $MyFoo = new Foo();
}

Now, if I call $MyFoo->do_stuff() from a theme file, such as, say, single.php, $MyFoo in fact *does_stuff* and I see the output in the page.

However, if I write a function in functions.php that wants to call $MyFoo->do_stuff() and then call that function from single.php the object is not found. In summary,

Works:

in themes/my_theme/single.php:
  if (isset($MyFoo))
    $MyFoo->do_stuff();

Does not work:

in themes/my_theme/functions.php:
  function do_some_foo_stuff() {
    ...
    if (isset($MyFoo)) {
       $MyFoo->do_stuff();
    } else {
       echo "no MyFoo set";
    }
    ...
  }
 themes/my_theme/single.php:
   if (isset($MyFoo))
     do_some_foo_stuff();

Outputs -> "no MyFoo set"

This may be totally unsurprising, but it's something I need/want to work, so if anyone can explain what is going on it'd be appreciated. Why can't the theme's functions file (or other plugin files in mu-plugins for that matter) find $MyFoo object?

+2  A: 

Read up on variable scope. The variable $MyFoo is not accessible within the function do_some_foo_stuff() unless you declare it global first;

function do_some_foo_stuff()
{
    global $MyFoo;
    ...
}
TheDeadMedic
Thanks, that's a working solution, but I guess I still don't understand the WP architecture well enough to understand why the plugin variable is directly accesible (without a global declaration) in the theme description files, such as single.php and home.php, but is out of scope in the functions.php file. Do you have any wordpress specific recommendations for reference material on variable scoping?
Bee
It is less to do with WordPress, and more about PHP variable scope. Theme files are merely PHP files included in the script, and will have access to variables within the parent scope. Personally, I try and avoid globals alltogether - I think a singleton class would much better suit your purpose here - http://www.tonymarston.net/php-mysql/singleton.html
TheDeadMedic