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!
January 27th, 2010 at 10:10 am
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!)
March 18th, 2010 at 4:59 pm
Thanks for the heads up. It is now updated to reflect the proper output.
May 24th, 2010 at 9:37 am
Nice one, this brought the end to a couple of hours of head scratching
August 12th, 2010 at 12:56 am
nice post.