Implementing PHP Iterator

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

aliasxneo
Forum Contributor
Posts: 136
Joined: Thu Aug 31, 2006 12:01 am

Post by aliasxneo »

Begby wrote:Here is the really simple way to do it.

Code: Select all

class DynamicObject implements IteratorAggregate, Countable
{
  private $details = array(); 
  
  //.. stuff

  
  // This is the method needed for the IteratorAggregate interface
  public function getIterator()
  {
     return new ArrayIterator($this->details) ;
  }

  // It threw this in here as well which is what is needed for the countable interface which you can use in place of
  // numAttributes()
  public function count()
  {
     return count($this->details) ;
  }

}


$test = new DynamicObject() ;

// ...

// use IteratorAggregate
foreach ($test as $key => $value)
{
  // do stuff
}

// Use Countable
echo count($test) ;
Thanks, I had this code working before (hadn't had time to post yet) but IteratorAggregate is the implementation I used.
Post Reply