Ferry Kobus
Ferry Kobus

Reputation: 2039

Run php variables as it was an if statement

I've got 3 variables:

$left_side = "'Username'";
$equation = "==";
$right_side = "'Username'";

I want to test these variables as it was an if statement like so:

if($left_side $equation $right_side) {
    // do something
} else {
    // do something else
}

I know this works:

if(eval("return ".$left_side." ".$equation." ".$right_side.";")) {
    // do something
} else {
    // do something else
}

I always tought it's 'not good' to use eval. Especially when you try to run user input.

Is there an other way to do this? I tried to google it, but it's not my friend to day ;)

Upvotes: 2

Views: 123

Answers (5)

gonzalo123
gonzalo123

Reputation: 11

eval() is evil, but call_user_func() is evil too and every framework uses this function in one place or another.

Tools aren't evil. They are just tools. Evil is the way that we use them.

As Uncle Ben said: Great power involves great responsibility :)

Upvotes: 0

Mahfud Harun
Mahfud Harun

Reputation: 947

I find this trick

http://gonzalo123.com/2012/03/12/how-to-use-eval-without-using-eval-in-php/

the idea is create a temporary file with the PHP source code, include this file with the standard PHP’s include functions and destroy the temporary file.

Upvotes: -2

Viktor S.
Viktor S.

Reputation: 12815

You may do something like this:

function testValues($val1, $equation, $val2) {
   $res = false;
   switch($equation) {
      case "==":
          $res = $val1 == $val2;
          break;
      case ">":
          $res = $val1 > $val2;
          break;
      //....
      default:
         throw new Exception("Unknown operator");
   }
   return $res;
}

and than use it like:

 if(testValues($left_side,$equation,$right_side)) {
     //do something
 } else {
    //do something
 }

Upvotes: 3

Mihai Iorga
Mihai Iorga

Reputation: 39724

You could use switch:

$left_side = "'Username'";
$equation = "doublequal";
$right_side = "'Username'";

switch($equation){
    case 'doublequal':
        if ($left_side == $right_side) {
             // code
        }
    break;
    //......
}

You should never use eval() especially with user input.

Upvotes: 2

webmonkey
webmonkey

Reputation: 1093

eval is evil. And no, there's no other (easy) solution, but maybe this one helps:

if ($equation == "==") {
    if ($left_side == $right_side) {
        // ... your code goes here.
    } else {
        // Do some other stuff.
    }
}

Upvotes: 2

Related Questions