开发者

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

开发者 https://www.devze.com 2023-01-29 09:52 出处:网络
I have things like this using eval(): $result = eval(\"return \".$value1.$operator.$value2.\";\"); Where the operator is from a variable, or a db field.

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 conc开发者_开发技巧ern 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.


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

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


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号