使用eval()
时遇到问题。我被迫将字符串存储在稍后执行的数组中。
现在,在字符串中存储字符串已经没有问题了。但是我如何在其中存储数组呢?由于我无法访问该变量,因此我希望将数组直接存储到该字符串中。
查看这段代码:
// ----------------------
// -- 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 )
{
...
}
除了数组 $arParams
之外,一切都运行良好。
出现错误:PHP 解析错误:语法错误,意外的 ')',期望 '(' in ... (441) :第 1 行 eval() 代码
有什么问题吗?
我可以在不使用 serialize()
的情况下执行此操作吗?
编辑:
我已经建立了正在发生的事情的表示。如果你让它运行,那么它就被修复了:
$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>";
}
最佳答案
当您在经过 eval
处理的字符串中运行函数 a()
时,变量 $ar
不再存在。这会触发错误,导致 eval()
失败。
由于您使用的是eval()
,因此一种快速而肮脏的黑客方法来修复它似乎是合适的。 ;-)
不要这样做:
$run = " a('".$str."', \$ar); ";
你可以这样做:
$run = " a('$str', ". var_export($ar, true) ."); ";
如果您要echo
它,这将导致字符串$run看起来像这样:
a('something', array(
'a' => 'value1',
'b' => 'value2',
));
所以现在您将数组直接传递到函数调用中,而不是传递变量。
关于php - 将数组存储在字符串中并稍后传递给 eval(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12568095/