Interesting PHP Quirk w/require_once

12 Sep

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();
?>

One Response to “Interesting PHP Quirk w/require_once”

  1. Shtepsell May 25, 2011 at 6:38 am #

    Аудио-Видео, Бытовая техника со склада. Весь ассортимент. Стиральные машины, телевизоры, встройка, холодильники, кондиционеры, посудомоечные, швейные машины и другое. Бесплатная организация доставки по Киеву. Гарантия. Складские цены.
    Тел.: (44) 233-03-96, (44) 332-60-75, (67) 947-19-49, моб. (67) 947-19-49
    Web: http://www.shtepsell.net.ua

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 88 other followers

%d bloggers like this: