Tuesday, August 02, 2005

 

PHP scope when require()'ing

I know I whined about PHP in my last post, but this behavior ticked me off enough to write once again about the language I love to hate.

if you require() or include() a file, it gets the scope of the caller. So if you have a file like so:

$foo = read_some_db_table();
foreach($foo as $name => $value) {
        $libray_variable[$name] = $value;
}
# Define library functions and classes that use $library_variable

And the if you do a "require()" (or a "require_once()") when you have, say, a $name (or $foo or $value. And, of course, $library_variable, but presumably the risk is lower with prefixed names) variable, it gets clobbered by the required file. To avoid this, you have to stuff the init logic into a function:

function library_init() {
        global $library_variable;
        $foo = read_some_db_table();
        foreach($foo as $name => $value) {
                $libray_variable[$name] = $value;
        }
}

library_init();
# Define library functions and classes that use $library_variable

Okay, maybe I should figure out a better than than using a global to avoid hitting the database more than once. But still, I don't see any good use for having required files use the same scope. It binds you too tightly to the code you're loading: Variables you defined could effect it, and variables it defines could effect you. It's not an abstraction if you have to know implementation details to use it safely.

Once again, the behavior is well documented, but this doesn't seem like a good excuse to me. "Didn't you read the signs? The dragon eats someone every week!"


Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?