2

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)

Machavity
  • 30,841
  • 27
  • 92
  • 100
YsoL8
  • 2,186
  • 5
  • 29
  • 47
  • To help people understand the issue better you should probably add a link to the previous question: http://stackoverflow.com/questions/5065294/can-array-values-be-accessed-by-variable-variables/5065373#5065373 – xzyfer Feb 21 '11 at 12:42

4 Answers4

2

Try

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

or

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

  • I think the second line would work for single values, but it's choking on the array's I.m searching for. I get a PHP error on an unexpected '[' which is the opening bracket for the array reference. – YsoL8 Feb 21 '11 at 12:37
  • i get errors when using double quotes , maybe this will point you in the right direction: ` Parse error: syntax error, unexpected T_LNUMBER in /var/www/index.php(19) : eval()'d code on line 1 Call Stack: 0.0006 645576 1. {main}() /var/www/index.php:0 0.0007 646552 2. sss() /var/www/index.php:22 bool(false) ` – Poelinca Dorin Feb 21 '11 at 13:27
  • @YsoL8 I updated my answer. I changed double quotes to single quotes. Did you try it with single quotes instead of double quotes? –  Feb 21 '11 at 22:34
1
$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!

Poelinca Dorin
  • 9,577
  • 2
  • 39
  • 43
0

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
xzyfer
  • 13,937
  • 5
  • 35
  • 46
  • That adds a value to the $_GLOAL array, right? I need to take a value - but see the answer I've given. – YsoL8 Feb 21 '11 at 13:13
0

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.

YsoL8
  • 2,186
  • 5
  • 29
  • 47