Call methods of objects in array using array_map?
In PHP 5.3 you can do:
$props = array_map(function($obj){ return $obj->getProp(); }, $objs);
(see anonymous functions)
Of course this will still be slower than using a for
loop as you have one function invocation per element but I think this comes closest to what you want.
Alternatively, which also works in prior to PHP 5.3 and might fit better to your style guidelines:
function map($obj) { return $obj->getProp();}$props = array_map('map', $objs);
Or (again back to PHP 5.3) you could create a wrapper function like this (but this will be the slowest possibility I think):
function callMethod($method) { return function($obj) use ($method) { return $obj->{$method}(); };}$props = array_map(callMethod('getProp'), $objs);