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:

JavaScript

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:

JavaScript

However this leaves me with a sort of burning desire to simplify this (I use it quite often). I would like a functionality like:

JavaScript

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:

JavaScript

Usage:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement