|
|
|
|
||||||
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 |
|
Messages: n/a
Hébergeur: |
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... Anyone ? |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
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 |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
> 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... > > Anyone ? I think you would like the Visitor pattern. |
|
|
|
#4 |
|
Messages: n/a
Hébergeur: |
DigitalBase write:
> 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); $idList=array_map(create_function('$group','return $group->getId();'),$groups); |
|
![]() |
| Outils de la discussion | |
|
|