我是php新手,我想有一个这样的条件语句:
if ($foo != 'Any') { $condition .= '$this_foo == $foo &&';}
if ($bar != 'Any') { $condition .= '$this_bar == $bar &&';}
if ($txt != 'Any') { $condition .= '$this_txt == $txt &&';}
$condition .= '$num1 > 0 && $num2 < 1000';
if (...[php would parse the $condition variable])
{
someoperations
}
if语句解析变量$condition的正确语法是什么?因此,条件语句依赖于其他变量,并防止长嵌套条件语句。
提前感谢!
这并不完全是解析,但是您可以在执行代码时评估您的条件。
$condition = true;
if ($foo != 'Any') { $condition = $condition && ($this_foo == $foo);}
if ($bar != 'Any') { $condition = $condition && ($this_bar == $bar);}
if ($txt != 'Any') { $condition = $condition && ($this_txt == $txt);}
$condition = $condition && ($num1 > 0 && $num2 < 1000);
if ($condition)
{
someoperations
}
假设$foo != 'Any'
= true
,结果是
$condition = true && ($this_foo == $foo) && ($num1 > 0 && $num2 < 1000);
让我们假设$this_foo == $foo
, $num1 == 45
和$num2 == 2300
$condition = true && true && (true && false);
$condition = false;
我相信你想要的是
if (eval("return " . $condition)) {...}
确保在解析失败时检查FALSE情况