将 if 语句的条件分配给变量

时间:2021-07-01 21:01:15

标签: php

是否可以将条件语句赋给变量并在 if 语句中使用它?例如,我有以下代码,其中 if 语句中的条件会不时更改:

<?php       
   $x = 2;
   
   //This "x > 5" value will come from a database
   $command = "x > 5";//Some times this value might be x > 5 || x == 1
  
   if($command)//This will always be true no matter what since the content of the $command is not empty
        echo "x is bigger than 5";
   else
        echo "x is smaller than 5";//I want this line to get executed since x is smaller than 5 in this case
?>

预期输出为 x is smaller than 5,但我得到的是 x is bigger than 5

1 个答案:

答案 0 :(得分:1)

您需要使用 eval()$command 必须在变量之前包含 $,因此它是有效的 PHP 语法。

$x = 2;
$command = '$x > 5';
$result = eval("return ($command);");
if ($result) {
    echo "x is bigger than 5";
} else {
    echo "x is smaller than 5";
}

由于 eval() 可以执行任意代码,因此您应该非常小心允许放入 $command 的内容。

相关问题