Preforming math stored in variables

前端 未结 4 1517
借酒劲吻你
借酒劲吻你 2021-01-21 11:03

I have 3 variables like this: $first = 2; $second = 5; $operation = \'*\';

how can I programaticly assign the solution to this math problem to the $answer variable? I ha

4条回答
  •  庸人自扰
    2021-01-21 11:21

    It works fine for me:

    var_dump(eval("return $first $operator $second;"));
    

    But eval is evil. You should better use a function like this:

    function foobar($operator)
    {
        $args = func_get_args();
        array_shift($args);
        switch ($operator) {
        case "*":
            if (count($args) < 1) {
                return false;
            }
            $result = array_shift($args) * array_shift($args);
            break;
        /*
            …
        */
        }
        if (count($args)) {
            return call_user_func_array(__FUNCTION__, array_merge(array($operator, $result), $args));
        }
        return $result;
    }
    var_dump(foobar("*", 3, 5, 7));
    

提交回复
热议问题