我可以在PHP中使用运算符作为函数回调吗?

Joh*_*ise 5 php operators

假设我有以下功能:

function mul()
{
   return array_reduce(func_get_args(), '*');
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用*运算符作为回调函数?还有其他方法吗?

cle*_*tus 8

在这种特定情况下,使用array_product():

function mul() {
  return array_product(func_get_args());
}
Run Code Online (Sandbox Code Playgroud)

在一般情况下?不,您不能将运算符作为回调函数传递给函数.你至少必须将它包装在一个函数中:

function mul() {
   return array_reduce(func_get_args(), 'mult', 1);
}

function mult($a, $b) {
  return $a * $b;
}
Run Code Online (Sandbox Code Playgroud)


Rag*_*geZ 5

您提供的代码不起作用,但您可以执行类似的操作.

function mul()
{
   return array_reduce(func_get_args(), create_function('$a,$b', 'return "$a * $b'));
}
Run Code Online (Sandbox Code Playgroud)

create_function允许你创建短函数(一个线程),如果你的函数越来越长,那么一个语句最好创建一个真正的函数来完成这项工作.

另请注意,单引号很重要,因为您使用的是美元符号,因此您不希望PHP尝试替换它们.