Re: array_map : to call a method on all objects
On Tue, 17 Jun 2008 11:07:07 +0200, DigitalBase <info@digitalbase.eu>
wrote:
> Hi,
>
> I am trying to call a method on all objects in an array.
>
> What i am doing now ::
>
> $groups = $user->getGroups();
> $newarray = array();
> foreach ($groups as $group) {
> $newarray[] = $group->getId();
> }
>
> I want to use a core feature of php to achieve this something like :
>
> $groups = $user->getGroups();
> array_map(array( ???? ,"getId"),$groups);
>
> Using the callback (first argument) i can call static methods, normal
> functions but i can not call methods of the object itself.
>
> I am not trying to start a discussion about performance, lazyness vs
> clean code etc. The point is, i have about 30 different methods that
> use that foreach() to call an object method, and everytime i write a
> foreach like this i am thinking there should be a better way...
Instead of a vanilla array, you could try to use an
ArrayObject/ArrayIterator, and define your own cascade of methods for
those. Alternatively, you could use a Composite pattern instead of an
array.
--
Rik Wasmus
....spamrun finished
|