虽然你可以使用eval()
做到这一点它依赖于变量是安全的。
这是很多,多安全:
function compute($num1, $operator, $num2) {
switch($operator) {
case "+": return $num1 + $num2;
case "-": return $num1 - $num2;
case "*": return $num1 * $num2;
case "/": return $num1/$num2;
// you can define more operators here, and they don't
// have to keep to PHP syntax. For instance:
case "^": return pow($num1, $num2);
// and handle errors:
default: throw new UnexpectedValueException("Invalid operator");
}
}
现在,您可以拨打:
echo compute($num1, $operators[array_rand($operators)], $num2);
也意识到我的回答并不需要'break',因为'return'会阻止交换机的其他部分执行。 +1 – sjagr 2014-12-05 16:38:46