是否可以使用PHP if语句包含所有变量?

Simple question really. I have come across an issue with work where it would be ideal to store >= <= and == into a variable to spit out into certain if statements wherever the case may be.

$numb1 = 5
$numb2 = 10
$option = >=

if($numb1 $option $numb2)

You can't put a var for testing this in a control instruction. This will return some : syntax error, unexpected T_VARIABLE

You could use some eval() to do it, but it's not advisable.

Perhap's you could make something different with the following :

$option=$_GET['option']; // or POST or something else...
$numb1 = 5;
$numb2 = 10;

switch($option) {
 case ">=":
    if($numb1 >= $numb2){//someting}
    break;
 case "<=":
    if($numb1 <= $numb2){//someting}
    break;
 case "==":
    if($numb1 == $numb2){//someting}
    break;
 default://something else if there is no $option
    break;
}

Or with a function like the following

function testVar($numb1,$numb2,$option)
{
   // Same switch
}

Not without using eval() which is generally considered a bad idea

Doing it directly like that, will only work using eval() - Using eval is not considered good practice. The main problem being that if the eval() statements takes in user input the user can inject php into your code. That's obviously bad. Refer this thread - When is eval evil in php?

What you'd be better off doing is created a series of switch statements for all the various operations such as 'greater than', 'less than', 'equals' and so forth...

The best thing to do for this is to make a function call or object wrapper, and then call the function to achieve the same result.

Example:

$func = '__my_eq_op_';


if ($func($numb1,$numb2)) {
  // Do stuff
}

The operator functions are then...

function __my_eq_op($a,$b) {
  return $a == $b;
}

function __my_gte_op($a,$b) {
  return $a >= $b;
}

function __my_lte_op($a,$b) {
  return $a <= $b;
}

For example. So you can really just break it down into using the functions instead.

For this:

if ($x == $y)

The parser sees 6 tokens... 1) KEYWORD IF: 2) LPAREN 3) VAR X 4) EQ 5) VAR Y 6) RPAREN

The parser uses these tokens to construct the AST for the IF conditional. Your thinking needs to move away from seeing the "==" as a variable. It's an operator!