Skip to content

Instantly share code, notes, and snippets.

@timwhitlock
Created May 22, 2015 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timwhitlock/d791a357520f73b4d2f9 to your computer and use it in GitHub Desktop.
Save timwhitlock/d791a357520f73b4d2f9 to your computer and use it in GitHub Desktop.
Shows the behaviour of array pointer functions called on custom Iterator objects
<?php
/**
* A warning to myself that custom iterators cannot entirely masquerade as native arrays for legacy code compatibility:
*
* - Custom classes implementing the Iterator interface work with `foreach`, but not with native array pointer functions.
* - Built-in iterators do work with `current`, `key` and `next` but the iterator methods cannot be overridden in subclasses.
*/
/**
* Entirely user-defined iterator class
*/
class CustomIterator implements Iterator {
private $a;
public function __construct( array $a = [] ){
$this->a = $a;
}
public function rewind(){
reset( $this->a );
}
public function key(){
return key( $this->a );
}
public function current(){
return current( $this->a );
}
public function valid(){
return is_int( key($this->a) );
}
public function next(){
next( $this->a );
}
}
/**
* Extending built-in iterator
*/
class ExtendedIterator extends ArrayIterator {
public function next(){
throw new Exception("You won't see this");
}
public function current(){
throw new Exception("You won't see this");
}
}
// Built-in class implementing Iterator
$test = new ArrayIterator( ['Skip this', ':-) all good'] );
next($test);
echo "Native ",current($test),"\n";
// Extending built-in functions
$test = new ExtendedIterator( ['Skip this', ':-/ overrides ignored'] );
next($test);
echo "Extend ",current($test),"\n";
// Completely custom user-defined class:
$test = new CustomIterator( ['Foo', 'Bar'] );
next($test);
echo "Custom ",current($test)?:":-( Just don't.","\n";
// Prints:
// Native :-) all good
// Extend :-/ overrides ignored
// Custom :-( Just don't.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment