Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use operators as function callback in PHP?

Tags:

operators

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?

like image 664
John David Koise Avatar asked Nov 07 '09 10:11

John David Koise


2 Answers

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;
}
like image 93
cletus Avatar answered Nov 08 '22 00:11

cletus


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.

like image 5
RageZ Avatar answered Nov 07 '22 23:11

RageZ