Skip to content

Instantly share code, notes, and snippets.

@snit-ram
Created September 27, 2011 02:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save snit-ram/1244146 to your computer and use it in GitHub Desktop.
Save snit-ram/1244146 to your computer and use it in GitHub Desktop.
Recursive Object iterator that reads protected and private properties
<?php
class ObjectIterator implements Iterator{
protected $object;
protected $reflectionObject;
protected $properties;
public function __construct( $object ){
$this->object = $object;
$this->reflectionObject = new ReflectionObject($object);
$this->properties = $this->reflectionObject->getProperties();
}
public function current(){
$item = current( $this->properties );
$item->setAccessible(true);
return $item->getValue( $this->object );
}
public function key(){
return current( $this->properties )->getName();
}
public function next(){
next( $this->properties );
}
public function rewind(){
reset( $this->properties );
}
public function valid(){
$key = key($this->properties);
return isset( $this->properties[$key] );
}
}
class RecursiveObjectIterator implements RecursiveIterator{
protected $iterator;
public function __construct( $object ){
if( is_array($object) ){
$this->iterator = new ArrayIterator( $object );
}else{
$this->iterator = new ObjectIterator( $object );
}
}
public function getChildren(){
return new RecursiveObjectIterator( $this->iterator->current() );
}
public function hasChildren(){
$current = $this->iterator->current();
return is_object( $current ) || is_array( $current );
}
public function current(){
return $this->iterator->current();
}
public function key(){
return $this->iterator->key();
}
public function next(){
$this->iterator->next();
}
public function rewind(){
$this->iterator->rewind();
}
public function valid(){
return $this->iterator->valid();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment