PHP Globals access issue when using a variable variable
I have this line in a class function:
$this_value = eval("return $$existing_value;");
This gives me the valu开发者_Go百科e I need when the $$existing_value
variable is set in the function, but I've found that I actually need to access the global scope in 99% of cases. I've tried rewritting it as $this_value = eval("return global $$existing_value;");
, but that returns a php error.
Does any know how I can do this correctly? (by the way, I am aware of the poor pratice this represents - but given the situation I cannot think of any other approaches)
Try
$this_value = eval('global $existing_value; return $$existing_value;');
or
$this_value = eval('global $$existing_value; return $$existing_value;');
$x = 3;
function sss()
{
$x = 1;
$y = eval('global $x; return $x;');
var_dump($y);
}
sss();
Will output int(3)
, so it works , but be carefull about double quotes and simple quotes!
Since eval is returning the value you need, you should be bale to just assign the return value to the $_GLOBAL
or $_SESSION
(preferred because $_GLOBAL
is evil) super globals.
$foo['bar'] = "pie";
$fixed_name_variable = "foo['bar']";
$_GLOBAL['foo'] = eval("return $$fixed_name_variable;");
echo $_GLOBAL['foo']; // pie
I've been re-thinking this process. I have relised that I can add a new array with a fixed name which the various processes contributing to this function can add the values needed, programatically, rather than trying to guess at names.
It'll also be far more secure and reliable than variable variables.
精彩评论