Overriding scope with the GLOBALS array

At some point in your PHP programming career you will want to read a global variable inside a function - I can pretty much guarantee that, because it is a very popular thing to do. Luckily, it is made easy for you by PHP through the $GLOBALS superglobal array, which allows you to access global variables even from within functions. When it comes to the $GLOBALS array it is quite simple: all variables declared in the global scope are in the $GLOBALS array, which you can access anywhere in the script.

To demonstrate this in action, consider the following script:

<?php
    
function foo() {
        
$GLOBALS['bar'] = "wombat";
    }

    
$bar = "baz";
    
foo();
    print
$bar;
?>

What do you think that will output this time? If you guessed "wombat", you would be correct - the foo() function literally alters a variable outside of its scope, so that even after it returns control back to the main script, its effect is still felt. You can of course read variables in the same way, like this:

$localbar = $GLOBALS['bar'];

However, that is quite hard on the eyes. PHP allows you to use a special keyword, GLOBAL, to allow a variable to be accessed locally. For example:

function myfunc() {
    GLOBAL
$foo, $bar, $baz;
    ++
$baz;
}

That would allow a function to read the global variables $foo, $bar, and $baz. The ++$baz line will increment $baz by 1, and this will be reflected in the global scope also.

 

Next chapter: Recursive functions >>

Previous chapter: Variable scope in functions

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar