YsoL8
YsoL8

Reputation: 2214

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 value 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)

Upvotes: 2

Views: 681

Answers (4)

user479911
user479911

Reputation:

Try

$this_value = eval('global $existing_value; return $$existing_value;');

or

$this_value = eval('global $$existing_value; return $$existing_value;');

Upvotes: 2

YsoL8
YsoL8

Reputation: 2214

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.

Upvotes: 0

xzyfer
xzyfer

Reputation: 14125

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

Upvotes: 0

Poelinca Dorin
Poelinca Dorin

Reputation: 9703

$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!

Upvotes: 1

Related Questions