Skip to content

Instantly share code, notes, and snippets.

@jaytaph
Created December 6, 2011 16:45
Show Gist options
  • Save jaytaph/1438895 to your computer and use it in GitHub Desktop.
Save jaytaph/1438895 to your computer and use it in GitHub Desktop.
Why lazy-loading getIterator does not work
// Our book class. We can still iterate over our chapters with the
// help of the iteratorAggregate implementation.
class Book implements IteratorAggregate {
protected $_title;
protected $_author;
protected $_chapters;
protected $_it = null;
function __construct($title, $author) {
$this->_title = $title;
$this->_author = $author;
$this->_chapter = array();
}
// This method must be implemented. It will return the actual iterator
function getIterator()
{
// Lazy loading the iterator
if (! $this->_it) {
// This will return the articles. Since they are inside an array, we
// can use the standard array-iterator.
$this->_it = new ArrayIterator($this->_chapters);
}
return $this->_it;
}
// Add a new chapter to this book
function addChapter(Chapter $chapter) {
$this->_chapters[] = $chapter;
}
function getTitle() {
return $this->_title;
}
function getAuthor() {
return $this->_author;
}
}
// Create a new book and add chapters to it
$book = new Book("About the iteratorAggregate", "Joshua Thijssen");
$book->addChapter(new Chapter("Foreword", "This is the introduction"));
$book->addChapter(new Chapter("Chapter 1", "Content"));
$book->addChapter(new Chapter("Chapter 2", "Content"));
print "All chapters from the book '" . $book->getTitle() . "', written by ".$book->getAuthor()." :" . PHP_EOL;
foreach ($book as $chapter) {
print "- " . $chapter->getTitle() . PHP_EOL;
}
// Add another chapter to our book
$book->addChapter(new Chapter("Epilogue", "Famous last words"));
// We cannot see the new chapter in the next loop, since our Book uses the already-initialized iterator.
print "All chapters from the book '" . $book->getTitle() . "', written by ".$book->getAuthor()." :" . PHP_EOL;
foreach ($book as $chapter) {
print "- " . $chapter->getTitle() . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment