Call methods of objects in array using array_map?

morphles picture morphles · Jul 27, 2011 · Viewed 22k times · Source

Suppose I have simple class like:

class MyClass {
  private $_prop;
  public function getProp() {return $this->_prop;}
  [....]
}

Now what I want to do somwhere not in scope of MyClass is to get array of $_prop from array of objects of MyClass($objs). This of course can be done with code like this:

$props = array();
foreach ($objs as $obj) {
    $props[] = $obj->getProp();
}

However this takes quote some lines, esp when formated in this way (and I have to use such formatting). So question is: if it is possible to do this using array_map? One way would be to use create function, but I don't really like that in php(lambdas in php are at least awkward and if i understand correctly its performance is like that of evaled code, but performance is beside the point here). I have tired searching quite a bit and failed to find any definetive answer. But I kinda have a feeling that it's not possible. I tried things like array_map(array('MyClass', 'getProp'), $objs), but that does not work since method is not static.

Edit: I'm using php 5.3.

Answer

Felix Kling picture Felix Kling · Jul 27, 2011

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