Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call methods of objects in array using array_map?

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.

like image 640
morphles Avatar asked Jul 27 '11 06:07

morphles


People also ask

What is the use of array_map?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.

Does array map preserve keys?

The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.

What is mapping in PHP?

A Map is a sequential collection of key-value pairs, almost identical to an array used in a similar context. Keys can be any type, but must be unique. Values are replaced if added to the map using the same key.


1 Answers

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); 
like image 87
Felix Kling Avatar answered Sep 20 '22 17:09

Felix Kling