Page 1 of 1

Iteration over an object

Posted: Tue Jul 11, 2006 3:30 pm
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.

Posted: Tue Jul 11, 2006 3:33 pm
by Christopher
Look at the SPL iterator classes.

Posted: Tue Jul 11, 2006 3:35 pm
by Ollie Saunders
here's a tutorial