Home >Backend Development >PHP Tutorial >PHP5+ introduces the concept of $GLOBALS delayed initialization_PHP tutorial
Today, when I use $GLOBALS['_SERVER'] instead of $_SERVER to access related environment variables, "_SERVER undefined" error will always be reported. The following use cases:
Use Case 1:
Print_r($GLOBALS);
There is no _SERVER related information in the output at this time:
Array
(
[GLOBALS] => Array
*RECURSION*
[_POST] => Array
(
)
[_GET] => Array
(
)
[_COOKIE] => Array
(
)
[_FILES] => Array
(
)
)
Use Case 2:
Print_r($GLOBALS);
Print_r($_SERVER);
At this time, the output contains _SERVER related information:
Array
(
[GLOBALS] => Array
*RECURSION*
[_POST] => Array
(
)
[_GET] => Array
(
)
[_COOKIE] => Array
(
)
[_FILES] => Array
(
)
[_SERVER] => Array
(
)
)
I checked the description of $GLOBALS in the PHP manual and quoted the comment of therandshow at gmail dot com:
therandshow at gmail dot com
As of PHP 5.4 $GLOBALS is now initialized just-in-time. This means there now is an advantage to not use
The $GLOBALS variable as you can avoid the overhead of initializing it. How much of an advantage that is
I'm not sure, but I've never liked $GLOBALS much anyways.
Tracking down the source, I found the description of the PHP5Changelog update log:
Unordered List ItemImproved Zend Engine, performance tweaks and optimizations
Unordered List ItemChanged $GLOBALS into a JIT autoglobal, so it's initialized only if used. (this may affect opcode caches!) www.2cto.com
718 ; When enabled, the SERVER and ENV variables are created when they're first
719 ; used (Just In Time) instead of when the script starts. If these variables
720 ; are not used within a script, having this directive on will result in a
721 ; performance gain. The PHP directives register_globals, register_long_arrays,
722 ; and register_argc_argv must be disabled for this directive to have any affect.
723 ; http://php.net/auto-globals-jit
724 auto_globals_jit = On
Finally I figured it out, in PHP5+, when auto_globals_jit = On is turned on, the $_SERVER variable and $_ENV variable will not be created when the script starts, but will be created when $SERVER and $ENV are used for the first time. So the above two use cases will appear.
Remarks:
Actual measurement conclusion:
auto_globals_jit setting is also affecting $_REQUEST superglobal in 5.3 It is not explicitly stated in documentation.
When auto_globals_jit = On is turned on at least in version 5.3.13, $_REQUEST will only be created the first time it is used.