Interesting PHP Quirk w/require_once

So as many of you astute readers may have noticed, we use PHP on the backend. Nathan and I ran into a curious quirk today; if you do a require_once() in a function’s context, the variables set in the required file are not visible as globals once the function returns, even to functions in the required file.

The moral of the story? If you use globals in your includes, put all the require_once()s that you might need at the top of your PHP. Don’t try and be clever with conditional inclusion of your libraries.

Here’s a simple test case to reproduce:

test.inc

$var = “foo”;
function f() {

global $var;
die($var);

}
?>

test.php

function a() {

require_once(‘test.inc’);

}
a();
f();
?>

Published by David Weekly

I like starting things. I founded PBworks (originally PBwiki) and am the cofounder of SuperHappyDevHouse and Hacker Dojo. I advise a dozen startups and am a mentor for Founders Institute, i/o Ventures, and Women 2.0.

4 thoughts on “Interesting PHP Quirk w/require_once

  1. Pretty nice post. I just stumbled upon your weblog and wanted to say that I’ve truly enjoyed surfing around your blog posts.
    After all I’ll be subscribing to your rss feed and
    I hope you write again soon!

  2. buzagda.ucoz.com mezilar.rurs.net mezilar.netii.net kazrazuru.netii.net kazrazuru.besaba.com vudomi.besaba.com vudomi.6te.net dusida.besaba.com dusida.netne.net coilis.besaba.com coilis.host22.com daijinn.besaba.com daijinn.host22.com bralen.besaba.com bralen.host22.com brazius.besaba.com gholbira.besaba.com gholbira.comxa.com +79185540950 (Viber,WhatsApp) Владимир

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.