简体   繁体   中英

PHP - if condition inside string

An easy question to ask, hope not to stupid.

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

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
  • etc

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

The eval() function is the easy way out here. Eg:

if(eval($condition)) {
    # do something #
}
else {
    # do something else #
}

It must be stressed that eval() is evil. It is very easy to make a website extremely insecure using eval() , even if you really know what you're doing. In particular, even if you're sure the code is safe now , it might not be so after you add a few features in totally different parts of the code.

That said eval() has its uses, particularly in quick-and-dirty single use scripts like migration scripts.

If you're writing a world-facing website, you need to take *extreme* care if using eval() . Very often, the necessary amount of care is more difficult than implementing some non- eval() solution.

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>

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

why not just do:

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

EDIT: Or even

$var = 0;
$condition = 0
if ($var != $condition){
    # do something #
}
else {
    # do something else #
}
  1. The contents of your $condition are not $var!=0 , but 0=0 (due to $ not being escaped ( \\$ ) within double quotes.

  2. You can do this with eval function.

  3. However, eval is Evil. Ask yourself if you really need to do this. If there is any other way, take it.

OK, you could use evil Eval. But if your condition is actually as simple as you propose, you could just use a regex to test the condition... No eval necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM