This may be a bit of a silly question and its one of convenience rather than functionality.
Assume we have the class:
class A {
public function getId() {
return rand(0,100); //For simplicity's sake
}
}
Let's say we have an array of objects of type A
, e.g. $array = [ new A(), new A(), new A() ];
Normally if I want to transform the array of all objects into an array of their IDs I'd do something like:
$idArray = array_map(function ($a) { return $a->getId(); }, $array);
However this leaves me with a sort of burning desire to simplify this (I use it quite often). I would like a functionality like:
$idArray = magic_array_map('getId', $array);
My question is, is there a way to call array_map (or similar function) by providing the function name instead of an actual callback? Something akin to array_map('count', $array)
but instead of strlen
provide a member method name.
In short, is there such a way built-in PHP or do I have to implement an array_map of my own to add this functionality?
You can create your own helper function to do what you want.
my_map_function($callback, $array) {
return call_user_func_array(callback, $array);
}
my_callback_function($array) {
//TODO
}
main() {
$array = [1, 2, 3];
$array = my_map_function('my_callback_function', $array);
}
Something like this ;)
Here you have more information
Why don't you make your own function and pass it to array_map()?
class A {
public function getId() {
return rand(0,100); //For simplicity's sake
}
}
$array = [ new A(), new A(), new A() ];
function getId(A $object) {
return $object->getId();
}
$ids = array_map('getId', $array);
print_r($ids);
From my point of view an elegant solution would be to create a Container class which would have a map method inside. Something like:
class A {
public function getId() {
return rand(0,100); //For simplicity's sake
}
}
class Container
{
protected $elements;
public function __construct($elements = array())
{
$this->elements = $elements;
}
public function map($method)
{
return array_map(function ($element) use ($method) {
return $element->$method();
}, $this->elements);
}
}
$container = new Container([new A(), new A(), new A()]);
var_dump($container->map('getId'));
The result would be something like:
array(3) { [0]=> int(70) [1]=> int(32) [2]=> int(90) }