Friday, December 5, 2008

PHP: Invoking a method with Map

Ever since I learned the basics of functional programming, I've been a fan of the map function. In the right context, it can be an elegant solution for array transformation. Of course, like anything, it can be misused. Using PHP's map, it's non-obvious how to make it invoke an instance method rather than a function. The following example illustrates how this can be accomplished.

class M
{
function double($a) {
return $a * 2;
}
}

$m = new M;
$list = array(1, 2, 3);
$list = array_map(array($m, 'double'), $list);
print_r($list);

Array
(
[0] => 2
[1] => 4
[2] => 6
)

1 comment:

Owen Raccuglia said...

Cool tip. Instance methods also let you map/filter arrays with stateful functions, without global variables. I appreciate any tip that helps fight ugly PHP ;)