PHP use string as operator

后端 未结 5 1731
我寻月下人不归
我寻月下人不归 2020-12-02 01:38

Say I have a string, $char. $char == \"*\".

I also have two variables, $a and $b, which equal \"4\" and \"5\" respectively.

How do I get the res

5条回答
  •  星月不相逢
    2020-12-02 02:21

    You can use eval() as suggested by @konforce, however the safest route would be something like:

    $left = (int)$a;
    $right = (int)$b;
    $result = 0;
    switch($char){
    
      case "*":
        $result = $left * $right;
        break;
    
     case "+";
       $result = $left + $right;
       break;
    // etc
    
    }
    

提交回复
热议问题