php如何使php解析 - 和+符号

use*_*354 1 php

如何使php看到这个变量像-+:

例:

$operation = '+';

$sum = $val1 $operation $val2 // I want to make $val1 + $val2;
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误,$操作变量是意外的,如何实现这一点?

Nie*_*sol 6

虽然你可以采取"懒惰"的方式,并做:

$sum = eval('return $val1 '.$operation.' $val2;');
Run Code Online (Sandbox Code Playgroud)

使用a会更安全switch:

switch($operation) {
    case "+": $sum = $val1 + $val2; break;
    case "-": $sum = $val1 - $val2; break;
    // define more operations here
    default: throw new Exception("Unrecognised operation ".$operation);
}
Run Code Online (Sandbox Code Playgroud)