PHP use string as operator

后端 未结 5 1700
我寻月下人不归
我寻月下人不归 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:19

    The easiest but most dangerous method is to use eval.

    $c = eval("return $a $char $b;");
    
    0 讨论(0)
  • 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
    
    }
    
    0 讨论(0)
  • 2020-12-02 02:30

    take a look at the eval() function. you will need to build a proper php command and run inside the eval() to extract out the result.

    0 讨论(0)
  • 2020-12-02 02:35

    safest method is a switch construct:

    function my_operator($a, $b, $char) {
        switch($char) {
            case '=': return $a = $b;
            case '*': return $a * $b;
            case '+': return $a + $b;
            etc...
        }
    }
    
    0 讨论(0)
  • 2020-12-02 02:39

    You can do with eval however I would not suggest using eval.

    If there is case operator can by anything you should check what operator is before using

    switch($char)
    {
      case '*':
        $result= $a * $b;
        break;
    
      case '+':
        $result= $a + $b;
        break;
    }
    
    0 讨论(0)
提交回复
热议问题