The following php code generates a PHP Parse error on the second eval() function call:
parse error, expecting
"identifier (T_STRING)"' or"variable (T_VARIABLE)"' or `"number (T_NUM_STRING)"' in demo.php(19) : eval()'d code on line 1
It appears that php is unable to handle the array reference $keys['key1'] inside the code to be evaluated. I have tried both versions 5.5.30 and 7.0.3 with similar results. Is this a bug in php, or am I doing something wrong? Is there a known workaround?
Since I am sure that some users will tell me that eval is evil and that I should not use it, what I am trying to do is populate a template form with predetermined values based upon an array of keys. I could write my own php code to do this, but it would be far more complex than simply calling eval.
<?php
$keys = array (
'Key1' => 'Successful',
);
$key1 = 'Key1';
echo 'PHP Version: ' . phpversion () . "\n";
$evaluated = 'Failure';
$php_works = '$evaluated = "value=$keys[$key1]";';
echo "Evaluating the following works: " . $php_works . "\n";
eval ($php_works);
echo $evaluated . "\n";
$evaluated = 'Failure';
$php_broken = '$evaluated = "value=$keys[' . "'key1'" . ']";';
echo "Evaluating the following does NOT work: " . $php_broken . "\n";
eval ($php_broken);
echo $evaluated . "\n";
?>
$php_broken = '$evaluated = "value=$keys[\'key1\']";';or similarevaling in the first place?$php_brokenstring by having'without concatenating the rest of the string after. You're muddling up the quotes.