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

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?

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.

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

<?php

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

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'";
}