After the previous WTF post about PHP, I was kinda hoping there won’t be any more unpleasant surprises regarding PHP… Nah, I was wrong.
There is one part of PHP that will never be truly clear to me. It’s the namespaces and what is regarded as global.
The typical scenario is – you have a file with some global variables, that you want available everywhere. So, in any function you need these, you just use the classical ugly-all-around construct
Wow, that’s enough for one post on its own… I mean, WTF?!
But anyways, we can live with that.
But then comes the best part – if you include (aka require) the file from within the function, all the variables suddenly “leave” the global scope, becoming local, and any other function that uses them as global all of a sudden cannot see them!
Pretty confusing, huh?
Let’s call this part of the post “why PHP cannot see my global variables?!”. But, that’s not the worst part.
Here comes the WTF part:
You can tell PHP that any variable is global (in other words, that PHP treats it as a global one), be it local, temporary, or really a global variable.
You just add the following line after the definition of your wanna-be global variable:
$GLOBALS['my_global_var'] = $my_global_var;
Pretty neat, huh? Is it now global or not? One thing is for sure, using the lovely global $my_global_var; construct now works no matter what. But if you think about it, and about what then means scope on PHP… rather don’t, it’s a head spinning journey into the abyss of madness… .