On the user-land
Think about things that you're trying to achieve. Why don't create fixed-code closures? You may easily do it with:
$operators = array(
"plus"=>function($x, $y)
{
return $x+$y;
},
"minus"=>function($x, $y)
{
return $x-$y;
},
"times"=>function($x, $y)
{
return $x*$y;
},
"div"=>function($x, $y)
{
return $x/$y;
}
);
//in PHP 5.5:
$result = $operators['plus']($num1, $num2);
//in PHP<5.5:
//$result = call_user_func_array($operators['plus'], [$num1, $num2])
Now you have two things: first, it's still dynamic code - and you may use it in expressions. Next, you're safe in terms of code evaluation - because you've defined the code by yourself. This approach also has advantage - you may define desired behavior as you wish. For instance, raise an exception for "div"
operator if second operand is zero.
"Easy" way
I'll notice this only to explain why this isn't a right way. You may use eval()
. It's like:
eval('$result='.$num1.$operators['plus'].$num2.';');
And then your result would be stored in $result
variable. It is about "easy" way, but not "right" way. The problem is - it is unsafe. Just think about it - you're executing some code, which is dynamic. If your code has nothing to do with user input, it may be applicable - in case, if you're checking your operands and operator before. But I still recommend to think twice before applying it.
If evaluation still needed
Then I recommend to look to some existing implementations. Here are some links: