Can I use operators as function callback in PHP?

前端 未结 4 1703
南旧
南旧 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:51

    The code you have provided wouldn't work but you can do something similar.

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

    create_function allows you to create short function (one liner), if your function is getting longer then one statement it's better to create a real function to do the job.

    Please also note the single quote are important because you are using dollar symbol so you don't want PHP to try to replace them.

提交回复
热议问题