PHP - 如果字符串中有条件 [英] PHP - if condition inside string

查看:28
本文介绍了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.

这篇关于PHP - 如果字符串中有条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆