Global variable scope in PHP
I 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:
$foo = 1;
function bar()
{
global $foo;
print $foo;
}
bar(); // gives 1
The exception is for superglobal variables, which are built-in variables available everywhere. Two examples are the array $_GET which stores the HTTP GET variables and $_POST for the variables of an HTTP POST request. Example:
function bar()
{
print $_GET['user']; // this works even inside a function because $_GET is superglobal
}
bar();
If the above code snippet is saved in test.php and you call it for example with the URL http://localhost/test.php?user=foo, then it will output foo.
A superglobal that you must know is $GLOBALS which is an array that contains all global variables, including itself. For example, the second code in this post can be rewritten as follows:
$foo = 1;
function bar()
{
print $GLOBALS['foo'];
}
bar(); // gives 1
Sometimes I loathe at the abundance of language. Right now, I want to make working code, not do a comparative study of programming languages. For example, I also want to make a plugin for Mnemosyne but guess what? They use Python!!! (another language I’ve never used)
Tags: function, global, http get, http post, mnemosyne, python, scope, superglobal, variable, wordpress










