Jump to content

[SOLVED] Loop through all objects of a class // gather objects


xtopolis

Recommended Posts

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
Share on other sites

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.