xtopolis Posted September 19, 2008 Share Posted September 19, 2008 Hi, I have a User class where I have a getPerms() method that returns an associative array. If I have 2 objects of the same class[user] like this: <?php $chris = new User(4); $bob = new User(7); ?> Then I have it call the same method, and print out nicely using a foreach, for each of the objects. <?php foreach($k->getPerms() as $k=>$v){ if($v){ echo "x\t|\t"; }else{ echo "\t|\t"; } } echo '<br />'; foreach($bob->getPerms() as $k=>$v){ if($v){ echo "x\t|\t"; }else{ echo "\t|\t"; } } ?> So how can I combine this into a loop that covers both(or as many as I create) objects? I just don't know how to gather the objects... Link to comment https://forums.phpfreaks.com/topic/124894-solved-loop-through-all-objects-of-a-class-gather-objects/ Share on other sites More sharing options...
corbin Posted September 19, 2008 Share Posted September 19, 2008 You could make the objects in an array.... $a = array(); $a[] = new Blah(); $a[] = new Blah(); foreach($a as $obj) { $obj->SomeThing(); } Link to comment https://forums.phpfreaks.com/topic/124894-solved-loop-through-all-objects-of-a-class-gather-objects/#findComment-645334 Share on other sites More sharing options...
xtopolis Posted September 19, 2008 Author Share Posted September 19, 2008 Thank you! I wasn't sure how I was supposed to put them into an array. You said this method: <?php $a[] = new User(); ?> But is there a way to gather them after the fact in a loop? example: <?php $a = new User(); $b = new User(); $users[] = $a;// how can I loop through this task ## $users[] = $b; ?> Or is after the fact gathering considered a bad practice? Link to comment https://forums.phpfreaks.com/topic/124894-solved-loop-through-all-objects-of-a-class-gather-objects/#findComment-645344 Share on other sites More sharing options...
aschk Posted September 19, 2008 Share Posted September 19, 2008 I think what you're looking for is actually a composite pattern. e.g. <?php interface iUser { public function doSomething(); } class user implements iUser { public function doSomething(){ echo "I am doing something\n"; } } class user_composite implements iUser { private $_users; public function addUser(iUser $user){ $this->_users[] = $user; } public function doSomething(){ foreach($this->_users as $user){ $user->doSomething(); } } } ?> Then to use your composite: <?php $test = user_composite(); $test->addUser( new User() ); $test->addUser( new User() ); $test->doSomething(); ?> Link to comment https://forums.phpfreaks.com/topic/124894-solved-loop-through-all-objects-of-a-class-gather-objects/#findComment-645552 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.