PHP-字符串中是否包含条件

问题描述:

一个简单的问题,希望不要愚蠢.

An easy question to ask, hope not to stupid.

$var=0;
$condition="$var!=0";
if($condition) {
    # do something #
}
else {
    # do something else #
}

很明显,上面的代码无法按预期工作.有没有从字符串获取if条件的好方法?还是我必须以某种令人不安的方式来解析字符串?

Obviously the code up there doesn't work as intended. Is there a nice way to obtain an if-condition from a string? Or do I have to parse the string in some disturbing way?

编辑 我对自己的解释不是很好. 事实是字符串可以包含您可以想象的任何可能的条件:

EDIT I didn't explain myself very well. The fact is that the string could contain any possible condition you can immagine es:

  • $ var> 0
  • $ var< 0
  • $ var == 0

我从xml文件中以字符串形式读取了这种情况,所以我不知道会发现什么.

I read this condition from an xml file as a string, so I don't know what I will find.

只是因为尚未有人发布.问问自己需要进行哪些比较.如果他们正在执行简单的数学运算,您可能希望在这样的架构中包含一些内容.

Just because no one has posted it yet. Ask yourself what comparisons need to be made. If they're doing simple math operations you might want to have something in the schema like this.

<conditions>
  <notEqual var="var" value="0" />
</conditions>

它将允许您具有多个条件,应该相对简单地进行解析并转换为php代码.

It'll allow you to have multiple conditions, should be relatively simple to parse and convert to php code.