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.
array_map(array('MyClass', 'getProp'), $objs)
where non static method will be called would be cleaner. One compact line. No need to create empty array. No need to manually loop and push objects onto array. Just give one array and take another. Of course this idea does not play well with oop and esp with dynamic lose typing that php uses... But still it could be done :) – Humpyarray_map
does. It doescallback($element)
for each $element in array. What you describe would be$element->callback()
instead. – Stephanystephenarray($obj, 'foo')
but that still would evaluate to$obj->foo($el)
becausearray_map
passes it's elements to that callback. It doesn't invoke a method on the elements. I'm not familiar with Haskell, but a quick glance at themap
function doesnt seem to suggest that it's different there. – Stephanystephenarray_map(array('MyClass', 'getProp'), $objs)
works (with PHP 5.3.3) – Hades