Can I use operators as a callback function in PHP?

Suppose I have the following function:

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

Can I use the * operator as a callback function? Is there another way?

+5
source share
4 answers

In this particular case, use array_product():

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

In general? No, you cannot pass an operator as a function callback. You would at least have to wrap it with a function:

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

function mult($a, $b) {
  return $a * $b;
}
+8
source

The code you provided will not work, but you can do something like this.

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

create_function ( ), , , .

, , , , PHP .

+5

, :

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

:

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 are well suited for a workflow solution. However, as a rule, it is a good habit when you are wondering if something is allowed in a particular language, just try and see what happens. You may be surprised at what some languages ​​allow, and if they do not, they will almost always give you some meaningful error message.

+1
source

PHP 5.3 has closures;)

0
source

All Articles