News Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Joshua Thijssen's Blog:
SPL Using the iteratorAggregate interface
December 06, 2011 @ 08:28:45

Joshua Thijssen has a recent post spotlighting a part of the Standard PHP Library (SPL) that implements that Traversable interface, the IteratorAggregate interface.

Together with its more famous brother "Iterator", they are currently the two only implementations of the "Traversable" interface, which is needed for objects so they can be used within a standard foreach() loop. But why and when should we use the iteratorAggregate?

He answers his question with an example - a book that contains chapters. With a normal iterator you'd have to define standard functions (like valid, rewind or key). Using the IteratorAggregate you can push items into an internal array (like chapters in a book) and call a "getIterator" method to get this set. He also takes it one step further and shows implementing the "Count" interface to make it easier to get a total count of the items in the iterator. Sample code is included to help clarify.

0 comments voice your opinion now!
spl iteratoraggregate interface traversable count


blog comments powered by Disqus

Similar Posts

KillerPHP Blog: PHP Interfaces: when and why you should use them instead of classes?

PHP-Tip-a-Day: PHP Tutorial: The Allegory of The Factory Pattern

James Morris' Blog: Removing Dependencies with the Observer Pattern (SplObserver, SplSubject)

Ryan Malesevich's Blog: iTunes Stats for Macintosh with PHP & MySQL Part 2

Web Mozarts: Give the Traversable Interface Some Love


Community Events





Don't see your event here?
Let us know!


series api configure community bugfix code release podcast wordpress application library introduction laravel language interview install threedevsandamaybe list symfony developer

All content copyright, 2014 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework