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...

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?

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();

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.