WordPress and Global Variables

I have a little piece of code inside my function.php file, and I can’t access a global variable. I copy this in a separate php file and I get ‘New value’ but not inside the theme’s function.php file:

$myVar = ‘test’;
function hello() {
global $myVar;
$myVar = ‘New value’;
}
hello();
echo $myVar;

Read More

and it prints out ‘test’;

Does WP has problems with globals? As far as I know, WP backend extensively uses global vars.

Related posts

Leave a Reply

1 comment

  1. In a simple PHP file this works for me — i.e. I get “New value”. Something must be missing from what you presented as your execution context.

    As for WP having a problem with globals, I think the more general statement is that PHP programs have a problem with globals in that they use/depend on waaaay too many of them. Unfortunately, it seems to be the nature of the beast.