【问题标题】:If logic (predicate expression) in a variable如果变量中的逻辑(谓词表达式)
【发布时间】:2019-07-05 12:56:30
【问题描述】:

我将比较运算符作为变量传递给 PHP Cli:

./test.php -k "command" -c ">0"

-k 中的命令生成结果,我已将其存储在 $result 中

我遇到的问题是我想将逻辑和比较运算符作为变量传递,这可能吗?

$result = 2;
$logic = ' >0';

if ( $result $logic ) echo "true"; 

但我明白了:

PHP 解析错误:语法错误,意外的 '$logic' (T_VARIABLE)

有什么想法吗?

【问题讨论】:

标签: php if-statement conditional-statements


【解决方案1】:

那样做是不可能的,但是你可以使用eval方法来做,像这样:

$result = 2;
$logic = ' >0';


eval('$logicResult = ' . $result . $logic .';');
if ( $logicResult ) echo "true"; 

不推荐使用eval 方法,因为它可能会在您的应用中引入安全漏洞。

【讨论】:

    【解决方案2】:

    虽然eval 可以解决问题,但它通常被认为是有害的。

    如果$logic 中可能的运算符实例的范围有限,最好使用 switch 语句或级联 if:

    $result = 2;
    $logic = trim(' <0');
    
    $op2 = substr($logic, 0, 2);
    $op1 = substr($logic, 0, 1);
    
    if ( $op2 == '>=') {
      $operand = substr($logic, 2);
      if ($result >= (int)$operand) { echo "true"; } 
    } elseif ( $op1 == '>' ) {
      $operand = substr($logic, 1);
      if ($result > (int)$operand) { echo "true"; } 
    } elseif ( $op1 == '=' ) {
      $operand = substr($logic, 1);
      if ($result == (int)$operand) { echo "true"; } 
    } elseif ( $op2 == '<=') {
      $operand = substr($logic, 2);
      if ($result <= (int)$operand) { echo "true"; } 
    } elseif ( $op1 == '<' ) {
      $operand = substr($logic, 1);
      if ($result < (int)$operand) { echo "true"; } 
    } else {
      echo "operator unknown: '$logic'";
    }
    

    【讨论】:

      【解决方案3】:

      正如@treyBake 的通知,您可以使用eval() - 将字符串评估为 PHP 代码

      <?php
      
      $result = 2;
      $logic = 'if(' . $result . '>0){echo "true";};';
      eval($logic);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多