dongying7847
dongying7847
2019-07-05 12:56
浏览 73
已采纳

如果变量中的逻辑(谓词表达式)

I'm passing the comparison operator as a variable to the PHP Cli:

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

The command in -k products a result and I've stored it in $result

The problem I'm getting is I want to pass the logic and comparison operator as variables, is this possible?

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

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

But I get:

PHP Parse error: syntax error, unexpected '$logic' (T_VARIABLE)

Any ideas?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanban4769
    duanban4769 2019-07-05 13:03
    已采纳

    It's not possible to do it that way, but you can do it using the eval method, like this:

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

    The eval method is not recommended, as it might introduce security flaws in your app.

    点赞 评论
  • doutouman6245
    doutouman6245 2019-07-05 13:05

    As @treyBake notice, you can use eval() - Evaluate a string as PHP code:

    <?php
    
    $result = 2;
    $logic = 'if(' . $result . '>0){echo "true";};';
    eval($logic);
    
    点赞 评论
  • douqin7086
    douqin7086 2019-07-05 13:34

    While eval does the trick, it is generally considered harmful.

    If the universe of possible operator instances in $logic is limited, better work with a switch statement or a cascaded 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'";
    }
    
    点赞 评论

相关推荐