伙计们,对于你们中的大多数人来说,这可能是一个简单的问题。但我对如何使用保存在变量中的运算符符号执行操作感到困惑。例子。
$first=5;
$second=5;
$operator="+";
$result=$first.$operator.$second;
echo $result;
但是 $result 只会打印 5+5。我想让它执行操作。
我的想法是将所有操作放在一个 if 条件下 -> if($operator == '+'){添加第一个和第二个操作数}。伙计们还有其他想法吗?
不使用 eval()
,您可以尝试使用内部带有 switch()
的自定义函数:
$first = 5;
$second = 3;
$operator = '+';
$result = mathOp($operator, $first, $second);
echo $result;
function mathOp($operator, $n1, $n2){
if(!is_numeric($n1) || !is_numeric($n2)){
return 'Error: You must use numbers';
}
switch($operator){
case '+':
return($n1 + $n2);
case '-':
return($n1 - $n2);
case '*':
return($n1 * $n2);
case '/':
if($n2 == 0){
return 'Error: Division by zero';
}else{
return($n1 / $n2);
}
default:
return 'Unknown Operator detected';
}
}