Link to home
Create AccountLog in
Avatar of rascal
rascalFlag for United States of America

asked on

Why global variables don't work in WordPress template parts?

Hi WP Experts!
I am relatively new to WP and coding a template part - I am finding that global variables do not work inside the template part and can't figure out why?

For example, please see the code below. The 'echo' statement displays an empty string, not the expected 'testing' value.

$myvar = "testing";
function test_func()
{
global $myvar;
echo $myvar;
}
test_func();

I Googled this condition and found that if I declare the variable $myvar as a global at the top of the page (even though it's the first time I'm using it), then assign the value of 'testing', the echo statement inside the test_func() then works as expected. But why?

Can anyone explain:

1) Why I need to declare the variable as a global in this case?
2) Is there a WP setting I can make somewhere centralized so that I don't need to worry about where globals work and where they don't (basically - so I can use global vars and have them work the way I expect them to work everywhere in the WP framework?)

Thanks experts!
ASKER CERTIFIED SOLUTION
Avatar of Jason C. Levine
Jason C. Levine
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
One possibility, if you really want global variables might be to use $GLOBALS which is an associative array and a superglobal PHP variable.  Most experienced programmers would not want global variables because of the risk of name collisions, and that's probably why WP goes out of its way to destroy any unknown variables.
Avatar of rascal

ASKER

Thanks Jason!
Avatar of rascal

ASKER

Sorry Ray, I had marked the question as answered before I saw your post. Thank you very much for your input anyway!
Not a problem at all - glad you've got a good answer!

Best to all, ~Ray