Can I use operators as function callback in PHP?

前端 未结 4 1701
南旧
南旧 2021-01-18 17:20

Suppose I\'ve the following function:

function mul()
{
   return array_reduce(func_get_args(), \'*\');
}

Is is possible to use the * operat

4条回答
  •  伪装坚强ぢ
    2021-01-18 18:00

    In this specific case, use array_product():

    function mul() {
      return array_product(func_get_args());
    }
    

    In the general case? No, you can't pass an operator as a callback to a function. You would at least have to wrap it in a function:

    function mul() {
       return array_reduce(func_get_args(), 'mult', 1);
    }
    
    function mult($a, $b) {
      return $a * $b;
    }
    

提交回复
热议问题