in wordpress , i set a variable in header.php
but in footer.php when I ech
I know you've already accepted the answer to this question; however, I think there's a much better approach to the variable scope problem than passing vars into the $GLOBALS
array.
Take the functions.php
file in your theme for example. This file is included outside the scope of the get_header()
and get_footer()
functions. In fact it supersedes anything else you might be doing in your theme (and I believe in the plugin scope as well--though I'd have to check that.)
If you want to set a variable that you'd like to use in your header/footer files, you should do it in your functions.php file rather than polluting $GLOBALS array. If you have more variables that you want to sure, consider using a basic Registry object with getters/setters. This way your variables will be better encapsulated in a scope you can control.
Here's a sample Registry
class to get you started if:
properties[ $index ] = $value;
}
/**
* @get mixed Objects stored in the registry
* @param string $index A unique ID for the object
* @return object Returns a object used by the core application.
*/
public function __get($index)
{
return $this->properties[ $index ];
}
# +------------------------------------------------------------------------+
# CONSTRUCTOR
# +------------------------------------------------------------------------+
public function __construct()
{
}
}
Save this class in your theme somewhere, e.g. /classes/registry.class.php
Include the file at the top of your functions.php
file: include( get_template_directory() . '/classes/registry.class.php');
Storing variables:
$registry = new Registry();
$registry->my_variable_name = "hello world";
Retrieving variables:
echo '' . $registry->my_variable_name . '
'
The registry will accept any variable type.
Note: I normally use SplObjectStorage as the internal datastore, but I've swapped it out for a regular ole array for this case.