在php中使用eval时出错

时间:2016-09-05 15:29:07

标签: php

我有一个示例代码:

$messages = array(
   array("mark" => "0 < {m} < 4.9", "message" => "BAD"),
   array("mark" => "5 < {m} < 10", "message" => "GOOD"),
);
$m = 3;
$message = "";
foreach ($messages as $row) {
   $condition = $row['mark'];
   $condition = str_replace('{m}', $m, $condition);
   $str = "$result = (bool)".$condition;
   eval($str);
   if($result) $message = $row['message'];
}
echo $message;

结果很糟糕,但它显示错误:Parse error: syntax error, unexpected '='。如何创意?

1 个答案:

答案 0 :(得分:1)

检查你的代码,除了双引号:表达式0 < 3 < 4.9在PHP中不是有效条件,所以你应该改变它:

$messages = array(
    array("mark" => "0 < {m} && {m} < 4.9;", "message" => "BAD"),
    array("mark" => "5 < {m} && {m} < 10;", "message" => "GOOD"),
);
$m = 3;
$message = "";
foreach ($messages as $row) {
    $condition = $row['mark'];
    $condition = str_replace('{m}', $m, $condition);
    $str = '$result = (bool)'.$condition;
    eval($str);
    if($result) $message = $row['message'];
}
echo $message; //output: BAD