Skip to content

Instantly share code, notes, and snippets.

@ftdebugger
Created June 19, 2013 09:08
Show Gist options
  • Save ftdebugger/5812864 to your computer and use it in GitHub Desktop.
Save ftdebugger/5812864 to your computer and use it in GitHub Desktop.
<?php
/**
* @author Evgeny Shpilevsky <evgeny@shpilevsky.com>
*/
class MyArrayIterator implements Iterator
{
/**
* @var array
*/
protected $array = array();
/**
* @param array $array
*/
public function __construct(array $array)
{
$this->array = $array;
}
/**
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
*/
public function current()
{
return current($this->array);
}
/**
* Move forward to next element
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
*/
public function next()
{
next($this->array);
}
/**
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
*/
public function key()
{
return key($this->array);
}
/**
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
*/
public function valid()
{
return isset($this->array[$this->key()]);
}
/**
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind()
{
reset($this->array);
}
}
class MyIteratorAggregate implements IteratorAggregate
{
/**
* Retrieve an external iterator
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
* @return Traversable An instance of an object implementing <b>Iterator</b> or <b>Traversable</b>
*/
public function getIterator()
{
return new ArrayIterator([1, 2, 3, 4]);
}
}
// Example
$iterator = new MyArrayIterator([1, 2, 3, 5]);
// output array
var_dump(iterator_to_array($iterator));
// output all values of array
foreach ($iterator as $value) {
var_dump($value);
}
// aggregate
$iteratorAggregate = new MyIteratorAggregate();
foreach($iteratorAggregate as $value) {
var_dump($value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment