问题
PROBLEM
So, I have this function to retrieve and proceed data from $_REQUEST, $_POST, $_GET or $_COOKIE arrays. I know which array to use only from function call. Simplified ex:
function gg( $name, $type="_REQUEST" ) {
return isset( $GLOBALS[$type][$name] ) ? $GLOBALS[$type][$name] : false;
}
And it works perfectly for calls like:
gg('var', '_GET');
gg('var2', '_POST');
But fails dramatically for:
gg('var');
// or
gg('var', '_REQUEST');
I managed to simplify this problem thou to 2 lines:
print_r( $GLOBALS['_REQUEST'] ); // this line returns nothing...
print_r( $_REQUEST ); // ...UNLESS this line is present anywhere in the code
Now, my obvious question is: Is there any necessity to initialize this $_REQUEST array to be present in $GLOBALS?
additional info:
php: 5.3.3-7
apache: 2.2.16
also I'm running on CGI/FastCGI
EDIT & SOLUTION
1
As found here the easiest solution would be to edit php.ini and change there value of auto_globals_jit from On to Off.
auto_globals_jit Off
2
Instead of this you can use ini_set() inside of your source file, however it didn't work for me...
ini_set("auto_globals_jit", "Off");
3
Yet another solution is to use $GLOBALS array to everything except $_REQUEST and for $_REQUEST requests call directly to $_REQUEST array :D
if($type == "REQUEST") return $_REQUEST[$name];
else return ${"_".$type}[$name]; // or $GLOBALS["_".$type][$name] if previous won't work
回答1:
Couldn't replicate this on my setup so it could possibly be CGI issue? As a workaround you could do something like this...
function gg( $name, $type="_REQUEST" ) {
return isset( ${$type}[$name] ) ? ${$type}[$name] : false;
}
Might be of interest:
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. http://www.php.net/manual/en/reserved.variables.globals.php
Update. See Post:
$_REQUEST not created when using variable variables?
回答2:
Just a tip:
function gg( $name, $type="_REQUEST" ) {
if($type=="_REQUEST")return $GLOBALS[$name];
return isset( $GLOBALS[$type][$name] ) ? $GLOBALS[$type][$name] : false;
}
Once I have made a function like yours:
function get_data($name)
{
if(isset($_GET[$name]))return $_GET[$name];
if(isset($_POST[$name]))return $_POST[$name];
}
回答3:
$_REQUEST is already a superglobal "which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods."
function gg( $name, $type="_REQUEST" ) {
switch ($type) {
case '_REQUEST':
return $_REQUEST[$name];
break;
case 'GLOBALS':
return $_GLOBALS[$name];
break;
// etc...
default
return false;
}
来源:https://stackoverflow.com/questions/8603953/request-superarray-not-initialized-in-globals-array