在php中使用vaiable as运算符

在php中使用vaiable as运算符,php,operators,Php,Operators,我正在尝试这样做: $identifier_1 = ">"; $identifier_2 = ">"; $relation = "and"; if($value $identifier_1 3 $relation $value $identifier_1 300) 这将代表: if($value > 3 and $value > 300) 基本上有三种方法 I.使用eval。这是一个强大的选项,但在涉及用户输入时也相当危险 $op1 = ">"; $op2 =

我正在尝试这样做:

$identifier_1 = ">";
$identifier_2 = ">";
$relation = "and";

if($value $identifier_1 3 $relation $value $identifier_1 300)
这将代表:

if($value > 3 and $value > 300)

基本上有三种方法

I.使用eval。这是一个强大的选项,但在涉及用户输入时也相当危险

$op1 = ">";
$op2 = ">";
$op3 = "and";

$expr = "100 $op1 200 $op3 300 $op2 200";
eval("\$result = $expr;");
二,。使用函数而不是运算符

function more($a, $b) { return $a > $b; }
function less($a, $b) { return $a < $b; }
function _and($a, $b) { return $a && $b; }

$op1 = 'more';
$op2 = 'less';
$op3 = '_and';

$result = $op3($op1(100, 200), $op2(200, 300));
函数更多($a,$b){return$a>$b;}
无函数($a,$b){return$a<$b;}
函数_和($a,$b){返回$a&&$b;}
$op1=‘更多’;
$op2=‘更少’;
$op3='_和';
$result=$op3($op1(100200),$op2(200300));

三、 自己编写解析器并计算表达式。这在某种程度上是最“干净”的方法,但编程起来可能相当棘手——这取决于您想要支持哪些运算符。

PHP如何知道哪些运算符和哪些变量可以比较?我猜您不能,因为在if(BOOL\u EXPR)的布尔表达式中需要语言构造(保留字)您可以使用eval()运行存储在字符串中的代码,但我强烈反对这样做。这对性能有害(强制重新编译脚本),并可能带来安全风险。