I was开发者_开发技巧 trying to get the name of a superglobal variable through a GET parameter. I was told to pass only _VAR_NAME
(without the $
) in the get request, so in the program I have to access it through a variable variable: $$_GET['parameter_name']
.
Everything went fine except with $_SERVER
. To try what was wrong I just did a small php script to test what was happening. Here is the code:
<?php
// ¡¡ This does not work !!
$nombre = "_SERVER";
$var = $$nombre;
print_r($var);
// This works
$nombre = "_GET";
$var = $$nombre;
print_r($var);
?>
Is there any reason for the _SERVER
version not working?
I get the following error:
Notice: Undefined variable:
_SERVER
in ...
I'm not sure why you need this, I don't use variable variables (there are usually better ways).
You could do a simple switch based on your $nombre variable, there are not so many superglobal variables!
switch ($nombre) {
case "_SERVER" :
print_r($_SERVER);
break;
case "_GET" :
print_r($_GET);
break;
case "_POST" :
print_r($_POST);
break;
// ...
default:
echo "Unknown variable";
}
When auto_globals_jit
directive is enabled, the SERVER and ENV variables are created when they're first used (Just In Time) instead of when the script starts. PHP Manual warns about variable variables:
Usage of SERVER and ENV variables is checked during the compile time so using them through e.g. variable variables will not cause their initialization.
Possible solutions are:
- Using the PHP function
getenv()
instead of the SERVER variable. - Adding just the line
$_SERVER;
before, or at the beginning of the script. - Disabled the directive (in php.ini:
auto_globals_jit = Off
, or inside the script:ini_set('auto_globals_jit',0);
) - Using the key '_SERVER' in the array $GLOBALS (
$GLOBALS['_SERVER']
)
You can try the alternative syntax:
$var = $GLOBALS["_SERVER"];
print_r($var);
This is functionally equivalent to $$varvar
.
One more critical thing to check is if $_SERVER
itself is there. (If not, place an empty count($_SERVER);
expression at the start of your script.)
It can be absent if variables_order=
was modified in the php.ini
(though it should really just show up as empty array in recent PHP versions.)
It Works perfectly here for me. have you tried print_r ($_SERVER)
it might not be populated on your system.
make sure you have not unset it somewhere in your script.
Are you using it in a function or class?
The warning states that this cannot be used on superglobals within functions or classes.
Your best bet is the switch statement.
精彩评论