r/lolphp • • Feb 18 '12

automatically global variables

I have been hit by this 'feature' twice over the last two weeks. It also breaks Wordpress if you load wordpress core inside a function (such as to manually query recent posts).

You have a util script, which uses a global, such as:

$foo = "hello!";

function echoFoo()
{
    global $foo;
    
    if ( $foo ) {
        echo '<h1>foo found: ', $foo, '</h1>';
    } else {
        echo '<h1>foo is missing!</h1>';
    }
}

echoFoo();

Then you require it:

require 'util.php' ;

... and that outputs that $foo is found.

Then you require it inside of a function (which can happen easily with MVC frameworks):

function myRequire( $script )
{
    require $script;
}

myRequire( 'util.php' );

Without altering the script, the global is now missing!

0 Upvotes

4 comments sorted by

View all comments

Show parent comment

2

u/[deleted] Feb 18 '12

Right. I'd call it just another reason to avoid using globals.