如何让php看到这个变量,如-
或+
:
示例:
$operation = '+';
$sum = $val1 $operation $val2 // I want to make $val1 + $val2;
但是我得到一个错误,$ operation变量是意外的,如何实现呢?
答案 0 :(得分:6)
虽然你可以采取“懒惰”的方式并且做:
$sum = eval('return $val1 '.$operation.' $val2;');
使用switch
:
switch($operation) {
case "+": $sum = $val1 + $val2; break;
case "-": $sum = $val1 - $val2; break;
// define more operations here
default: throw new Exception("Unrecognised operation ".$operation);
}
答案 1 :(得分:0)
您可以使用变量函数
$functions = array(
'+' => 'plus',
'-' => 'minus',
'*' => 'multiply'
);
if (isset($functions[ $operation ]) {
$operation = $functions[ $operation ];
$result = $operation($val1, $val2);
}