|The Missing PHP Global|
|Written by David Conrad|
Page 1 of 2
A global variable is a global variable and that's all there is to it. But if you write PHP code to be used by other people, you might want to consider that this isn't always the case. Can you see where our puzzle is going wrong with its globals?
This is the sort of PHP puzzle that comes up when you are reusing some boiler plate code within an off-the-shelf system. You probably wouldn't make this mistake if you were writing the complete program from scratch.
As with many PHP problems, this one is all about scope and you might want to read up on a simpler problem before tackling this one see: A Question of Scope.
The basic rule of PHP scoping is that variables are local to whatever context they are declared in or used in.
If you write:
then in this case $myVariable is local to the function and hence, in this case, undefined. It doesn't matter that the local variable has the same name as the global variable you have already defined - it is still local.
To make a variable used within a function global you have to use the global keyword to declare it to be global. For example if you change the function to read:
then it all works as you would expect and $myVariable used in the echo statement is the global variable and hence the value "test" is echoed to the HTML.
So far so good but there is still scope for mistakes (pun intended).
An experienced PHP programmer was given the task of creating a small module to be used by other programmers. The module had a single global variable that set a base address for the rest of the module. The code, much simplified for the sake of an example, was something like:
This all worked perfectly and the module was issued to users.
The next day a strange bug was reported and on investigation it was discovered that the command inserted into the HTML read:
So where had the missing $baseURL gone?
At first it looked like some sort of automatic HTML parsing was stripping out the data,m leaving only the "///" but there seemed to be nothing working on the page after the PHP had created it.
So what exactly is the problem?
Remember that this code has been included into an existing PHP program and it isn't just running "standalone".
Turn to the next page when you are ready to find out.