开发者

using vaiable as operator in php

I am trying to do this:

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

if($value $identifier开发者_开发百科_1 3 $relation $value $identifier_1 300)

which will represent:

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


There are basically three ways.

I. Use eval. This is a powerful option, but also quite dangerous when user input is involved.

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

$expr = "100 $op1 200 $op3 300 $op2 200";
eval("\$result = $expr;");

II. Use functions instead of operators

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));

III. Write a parser and evaluate expressions on your own. This is somehow the "cleanest" way of doing this, but can be quite tricky to program - depends on which operators you want to support.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜