0

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.

bcmcfc
  • 25,966
  • 29
  • 109
  • 181

2 Answers2

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

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

Caner
  • 57,267
  • 35
  • 174
  • 180
1

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));
Spiny Norman
  • 8,277
  • 1
  • 30
  • 55