PHP Nested Functions using global variables

Web Development Add comments

Today I figured out the hard way some intricacies of using the global setting within nested functions. In PHP, if you want to load a variable from outside of your function, you first have to declare it as global before you use it inside your function. So Something like this.

$a = 1;
function test() {
    global $a;
    echo $a; // will output '1'
}

I assumed it worked similar to actionscript where anywhere you use a global variable it can find it. That isn’t always the case in PHP as I just found out. The global setting is merely a reference to the top level code, so issues can come up when you are using nested functions. So I had a function that did an include or two and had a function within that at some point and realized any variable that was within that first function was not accessible even if I globalized the variable. So here is what I was trying.

function simpleFunction() {
    $a = 1;
 
    function test() {
        global $a;
        echo $a; // will output nothing
    }
 
}

Nothing would output in this senario because my test function is looking on the top level code for that variable. Since my variable isn’t in the top level, there is an issue. So my solution was simple. Just declare the variable global in the top level and then use it wherever I want. Something like this.

global $a
 
function simpleFunction() {
    global $a;
    $a = 1;
 
    function test() {
        global $a;
        echo $a; // will output '1'
    }
 
}

So now the variable is declared in the top level even though I’m using it within a function and a nested function. It took me a bit of time to figure this out so hopefully someone else can learn from it. Enjoy!

4 Responses to “PHP Nested Functions using global variables”

  1. SPAIN Oscar.dR Says:

    Thanks man, very helpful! By the way, the comment in the last block of code has a mistake: {echo $a;} will output 1 ;) (I understood it anyway hehe!)

  2. CANADA jesse Says:

    Thanks for the heads up. It is now updated to reflect the proper output.

  3. UNITED KINGDOM Melon Creative Says:

    Nice one, this brought the end to a couple of hours of head scratching :)

  4. AUSTRALIA shaffy Says:

    nice post.

Leave a Reply

Powered by WP Hashcash

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in