Just-in-time $GLOBALS

Update—Turns out, this isn’t actually a bug. Rasmus Lerdorf has already explained this behavior in response to a bug report:

This is not a bug. It is a documented optimization feature. See http://php.net/manual/en/ini.core.php and look for the section on auto_globals_jit with the big pink warning which says, “Usage of SERVER and ENV variables is checked during compile time so using them through e.g. variable variables will not cause their initialization.”


I encountered an odd bug in PHP 5.3.10 while attempting to loop through all the major superglobals ($_SERVER, $_GET, $_POST, etc). Here is what I found, if you can shed any light on why this happens, or if you can confirm that it isn’t just me, I would greatly appreciate it!

Test Case

<?php
var_dump($GLOBALS['_SERVER']);
// These behave the same way:
// $var = '_SERVER'; var_dump($$var);
// var_dump(${$var});

Expected Behavior

$GLOBALS["_SERVER"]: array(27) {
...
}

Actual Behavior

NULL

Workaround

What makes this so strange is that if you access $_SERVER (or ${'_SERVER'}) directly in the code anywhere—even if it doesn’t actually get executed—this bug does not manifest itself! In other words, this works just fine:

<?php
var_dump($GLOBALS['_SERVER']);
exit;
$var = $_SERVER;

Leave a Reply

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