Skip to content
Advertisement

Call object member function on all array members

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?

Advertisement

Answer

One solution is to apply technique php call class function by string name (see final code snippet), into a function that maps that over the array:

function apply_member_function(string $method_name, array $array) :array {
    return array_map(function ($ob) {return $ob->$method_name();}, $array);
}

Usage:

$array_of_as = [ new A(), new A(), new A() ];
$array_of_ids = apply_member_function('getId', $array_of_as);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement