The following example demonstrates use of the global keyword:
<?php
$my_var = ‘Hello World’;test_global();
function test_global() {
// Now in local scope
// the $my_var variable doesn’t exist
// Produces error: “Undefined variable: my_var”
echo $my_var;
// Now let’s important the variable
global $my_var;
// Works:
echo $my_var;
}
?>
As you can see in the above example, the global keyword is used to important variables from the global scope. Seems to work fine, and it’s nice and simple, so why should you worry about using the global keyword?
There are three good reasons:
1. Reusing parts of the script is impossible
If a certain function relies on global variables, it becomes almost impossible to use that function in a different context. Another problem is that you can’t take that function, and use it in another script.
2. Solving bugs is much harder
Tracking a global variable is much harder than a non-global variable. A global variable could be declared in some obscure include file, which could take hours to find, although a good text editor / IDE could help with this.
3. Understanding the code in a year will be much more difficult
Globals make it difficult to see where a variable is coming from and what it does. You might know about every global during development, but after a year or so you’ll probably have forgotten at least half of them, and then you’ll be kicking yourself for using so many globals