bcmcfc
bcmcfc

Reputation: 26745

How to avoid using eval for a particular string of variables that needs to be executed

I have things like this using eval():

$result = eval("return ".$value1.$operator.$value2.";");

Where the operator is from a variable, or a db field.

How would I go about achieving the same result without using eval? Is it possible?

It's not a security concern as the values/operator aren't user entered, but it may be a performance concern if this comment at the PHP manual is anything to go by. Plus, if at some point I want to try out Facebook's HipHop I need to replace all uses of eval with something else.

Upvotes: 0

Views: 271

Answers (2)

Spiny Norman
Spiny Norman

Reputation: 8327

Well, I'm not sure about operators, but you can do something like this with function names:

function add($x, $y) {
    return $x + $y;
}

$value1 = 1;
$value2 = 2;
$func = "add";

$result = $func($value1, $value2);

You can even do this with builtin functions:

$func = 'array_sum';
$result = $func(array($value1, $value2));

Upvotes: 1

Caner
Caner

Reputation: 59148

if(strcmp($operator, "+") == 0) {  
  return   $value1 + $value2;
}  
else if(strcmp($operator, "*") == 0) {  
return   $value1 * $value2;  
}  
...  

As @Gumbo mentioned, you can also use switch()

Upvotes: 2

Related Questions