Iteration over an object

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

Post Reply
User avatar
Todd_Z
Forum Regular
Posts: 708
Joined: Thu Nov 25, 2004 9:53 pm
Location: U Michigan

Iteration over an object

Post by Todd_Z »

Code: Select all

class obj {
  private $vars;
  public function __construct ( ) {
    $this->vars = array();
  }
  public function __get ( $var ) {
    return $this->vars[ $var ];
  }
  public function __set ( $var, $val ) {
    $this->vars[ $var ] = $val;
  }
}
My question is whether or not its possible to iterate over the 'vars' object without making it public in the following way:

Code: Select all

$obj = new obj();
$obj->a = 1;
$obj->b = 2;
foreach ( $obj as $var => $val )
  echo "{$var}: {$val}\n";
Essentially I'm trying to make it look like the get and set methods aren't being overwritten at all, it would function exactly like an object with a list of private variables.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Look at the SPL iterator classes.
(#10850)
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

here's a tutorial
Post Reply