Can I use operators as function callback in PHP?

前端 未结 4 1726
南旧
南旧 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 17:46

    If I define your function and then do this:

    $arr = array(2,3,4,5,6);
    mul($arr);
    

    I get the following warning:

    Warning: array_reduce(): The second argument, '*', should be a valid callback in /home/azanar/Documents/Projects/testbed/test.php on line 6
    

    The other two answers here do well at addressing a working way of doing this. However, it is generally a good habit, when you wonder if something is allowed in a particular language, to just try it and see what happens. You might be surprised by what some languages allow, and if they don't, they're almost always going to give you some sort of meaningful error message.

提交回复
热议问题