PHP: Something to watch out when using global scope variables, or "why globals doesn't (seem to) work!?"

Okay, I guess this is probably a childish mistake for an experienced PHP-er, but I myself got busted tonight, and maybe I’m not the only one :-) So, here it is.

Consider the following small PHP program:

<?php
print_global_a();

$a = 10;

function print_global_a() {
        global $a;
        echo "$an";
}

What would be the output of this code? What?? 10?? Wrooong! Let’s save this as global.php and run it, see what happens.

giannis@ubuntu:~$ php global.php

giannis@ubuntu:~$

It outputs an empty new line… Okay, then maybe something wrong with the ‘globals’ keyword. Let’s try the $GLOBALS array instead:

<?php
print_global_a();

$a = 10;

function print_global_a() {
        echo $GLOBALS['a']."n";
}

Now let’s run it again:

giannis@ubuntu:~$ php global.php
PHP Notice:  Undefined index: a in /home/giannis/global.php on line 7

giannis@ubuntu:~$

It just got even worse; not only we still get an empty new line, we also get a big fat warning.

So, what is really wrong here? It is so simple, you probably noticed on the first glance, but if you didn’t, here it is: At the moment that the function is called the $a global variable is not yet set. Therefore, when we try to access it from within a function, we simply cannot, not because ‘globals’ is not working, but because it is not set in the first place. The fact that the definition of the function comes after the assignment may delude us to think that the variable will be set when the code in the function is executed.

So, in other words, the next time you may face a “globals” that doesn’t seem  to work, make sure that the variable is actually set at the point where the function is called.

Unfortunately, PHP is a tool that does not protect the programmer from doing nasty mistakes… I hope you found this interesting and helpful :-)

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>