Reputation: 3990
Having problems with eval()
. I am forced to store strings in an array that are exectuted later on.
Now, storing strings in the string is no problem. But how do I store an array in there? Since I will NOT have access to the variable, I want the array directly stored to this string.
See this code:
// ----------------------
// -- class A
$strId = 'id_1234';
$strClass = 'classname';
$arParams = array('pluginid' => 'monitor', 'title' => 'Monitor', ...);
$strClone = 'openForm(desktop(),"'.$strId.'","'.$strClass.'",'.$arParams.');';
$this->menu = array( "clone" => $strClone, ... );
// ----------------------
// -- class B
// loop through $this->menu, then..
{
eval( $this->menu[$item] );
}
// ----------------------
// -- class C
function openForm( $owner, $id, $class, $params )
{
...
}
Everything works perfectly except for the array $arParams
.
There is an error: PHP Parse error: syntax error, unexpected ')', expecting '(' in ... (441) : eval()'d code on line 1
What is the problem?
Can I do this without serialize()
?
EDIT:
I have set up a representation of what is going on. If you get this to run, then it is fixed:
$ar = array('a' => 'value1', 'b' => 'value2');
$str = "something";
$run = " a('".$str."', \$ar); "; // this line may be changed
// this is done to represent the loss of the variables in another class
unset($ar);
unset($str);
// $run is kept
eval( $run );
function a($str, $ar) {
echo "\$str=" . $str . "<br>";
echo "\$ar['a']=" . $ar['a'] . "<br>";
echo "\$ar['b']=" . $ar['b'] . "<br>";
}
Upvotes: 2
Views: 1056
Reputation: 13500
When you're running the function a()
in your eval
'ed string, the variable $ar
doesn't exist anymore. That's triggering an error, which causes the eval()
to fail.
Since you're using eval()
, a quick-and-dirty hacky way to fix it seems appropriate. ;-)
Instead of doing this:
$run = " a('".$str."', \$ar); ";
You can do this:
$run = " a('$str', ". var_export($ar, true) ."); ";
This will cause the string $run to look like this if you were to echo
it:
a('something', array(
'a' => 'value1',
'b' => 'value2',
));
So now you're passing the array directly into the function call, instead of passing a variable.
Upvotes: 2
Reputation: 3990
I now use this hack:
$strParams = " array(";
foreach($arParams as $strKey => $strVal) {
$strParams .= "'".$strKey."' => '".$strVal."',";
}
$strParams = substr($strParams, 0, -1) . ") ";
// later on
... => " openForm(desktop(),'".$strId."','".$strClass."',".$strParams."); "
Upvotes: 0
Reputation: 407
Yes, change $arParams
to this:
$arParams = 'array("pluginid" => "monitor", "title" => "Monitor", ...)';
Upvotes: 0