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)

1

4 Answers 4

2

Try

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

or

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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) `
@YsoL8 I updated my answer. I changed double quotes to single quotes. Did you try it with single quotes instead of double quotes?
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!

Comments

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

1 Comment

That adds a value to the $_GLOAL array, right? I need to take a value - but see the answer I've given.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.