Possible Duplicate:
Can I use operators as function callback in PHP?
Is it possible to use an operator like a function in PHP?
For example, I’ve written a little function that looks like this:
function aggregate($values,$function,$initial=null) {
$agg = $initial === null ? array_shift($values) : $initial;
while($values) {
$agg = call_user_func($function,$agg,array_shift($values));
}
return $agg;
}
I’m wondering if it would be possible to call it with something like
agggregate(array(1,2,3),'+');
Which would yield 1+2+3=6.
If not, I guess I could call it like this:
agggregate(array(1,2,3),function($a,$b){return $a+$b;});
But it’s not as compact.
I just noticed this is identical to array_reduce; it’s not necessary to point this out 😉
Using the anonymous function is the way to go in PHP. Unfortunately it does not have something like python’s
operatormodule.