2

有问题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

There is an error: PHP Parse error: syntax error, unexpected ')', expecting '(' in ... (441) : eval()'d code on line 1

问题是什么?我可以不这样做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>";
}
4

3 回答 3

2

当您a()eval'ed 字符串中运行该函数时,该变量$ar不再存在。这会触发错误,从而导致eval()失败。

由于您正在使用eval(),因此一种快速而肮脏的 hacky 方法来修复它似乎是合适的。;-)

而不是这样做:

$run = " a('".$str."', \$ar); ";

你可以这样做:

$run = " a('$str', ". var_export($ar, true) ."); ";

这将导致字符串 $run 看起来像这样echo

a('something', array(
  'a' => 'value1',
  'b' => 'value2',
));

所以现在您将数组直接传递给函数调用,而不是传递变量。

于 2012-09-25T08:46:18.110 回答
0

是的,改成$arParams这样:

$arParams = 'array("pluginid" => "monitor", "title" => "Monitor", ...)';
于 2012-09-24T15:30:08.490 回答
0

我现在使用这个技巧:

$strParams = " array(";
foreach($arParams as $strKey => $strVal) {
   $strParams .= "'".$strKey."' => '".$strVal."',";
}
$strParams = substr($strParams, 0, -1) . ") ";

// later on
... => " openForm(desktop(),'".$strId."','".$strClass."',".$strParams."); "
于 2012-09-25T08:44:55.120 回答