In our second article on the standard PHP library, David Fells explains the new Arrray object, introduces Iterators and the ArrayIterator, and discusses some practical examples of their usage. This article assumes a knowledge of how Exceptions work in PHP 5.
In the first installment of my series on SPL, we talked about Exceptions. If you have not read it and are not yet familiar with how exceptions work in PHP 5, please do so here (http://www.devshed.com/showblog/6520/The-Standard-PHP-Library-Part-1). This article assumes knowledge of the Exception class. This installment will cover the new Array object, introduce Iterators and the ArrayIterator, and discuss some practical examples of their usage.
An iterator is, as the name implies, an object that traverses the contents of another object. The object may be a simple array data type or it may be a complex class, but by using iterators, we can standardize the way we traverse objects. The more important concept, however, is providing a way to traverse an object without exposing its internal data structure. In addition to providing a standard interface for object traversal and keeping the internal structure of the object being traversed private, it is common to iterate an object using a filter or to have multiple pending traversals on a single object. Using an iterator allows us to do all this.
The big picture objective behind using special objects such as Iterators is to achieve what is called loose coupling. Loose coupling is present when the internal behavior of objects can change without affecting the objects that interact with them. It also means that private class data is kept private and is not directly accessible to outside objects. This allows classes to store internal data in whatever way they like without forcing other objects to make assumptions about data storage when attempting to directly access class data. The new features in PHP 5 and the introduction of the SPL allow PHP developers to take advantage of these concepts in ways that were previously not possible. To get an overview of the new features in PHP 5 if you are not already familiar with them, have a look at my article: "What's New in PHP 5" (http://www.devshed.com/c/a/PHP/Whats-New-in-PHP-5/).
We will discuss the new ArrayObject class as a precursor to our discussion on iterators, as the ArrayObject class serves as an excellent example for simple iteration routines.