Global variable scope in PHP
Wednesday, June 11th, 2008 by Agro RachmatullahI need to do some WordPress hacking so I’m actually playing around with PHP at this time. What surprised me recently was that this code doesn’t work as I expected:
$foo = 1;
function bar()
{
var_dump(isset($foo));
}
bar(); // gives bool(false)
It turns out that in PHP global variables are not automatically available inside functions, to prevent accidental overriding. (I have a C-ish background) To use a global variable inside a function, we need to use the global keyword: