John David Koise
John David Koise

Reputation: 73

Can I use operators as function callback in PHP?

Suppose I've the following function:

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

Is is possible to use the * operator as a callback function? Is there any other way?

Upvotes: 5

Views: 403

Answers (4)

bobflux
bobflux

Reputation: 11581

PHP 5.3 has closures ;)

Upvotes: 0

RageZ
RageZ

Reputation: 27313

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.

Upvotes: 5

cletus
cletus

Reputation: 625147

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;
}

Upvotes: 8

Ed Carrel
Ed Carrel

Reputation: 4254

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.

Upvotes: 1

Related Questions