HomePHP Iterators in the Simplest Sense: Traversing Different Data Structures
Iterators in the Simplest Sense: Traversing Different Data Structures
Here we are again. Welcome to the second tutorial of the series “Iterators in the simplest sense.” Just in case you didn’t know, this series introduces Iterators in PHP 4 – PHP 5, explaining their basic concepts, and teaches you how to use them in practical projects, which can be utilized as part of larger PHP applications.
As you’ll probably recall, in the first tutorial of this series, I briefly explained the theory behind Iterators in PHP, and highlighted some of their benefits by constructing an array iterator class. As you know, this array iterator was created as a subclass of the abstract “Iterator” class that I defined at the beginning of the first article, demonstrating that building an iterating programming structure in PHP is not only easy, but also fun and instructive.
Nevertheless, an array iterator class isn’t very useful when evaluated as a standalone structure, isolated from other programming modules that might exist within the same Web application. In accordance with this, the real power of such a structure is leveraged when used as a building block of larger programs, which can use at a lower level some (or all) the methods provided by the array iterator.
In order to illustrate how you can implement an array iterator within your own PHP applications, without sacrificing much of its functionality, over this second installment of the series, I’ll show you how different data structures can be traversed by the same set of abstract methods (called an interface) defined previously within the base abstract “Iterator” class. Following this approach, I’ll provide a common interface for iterating over distinct types of data structures, no matter if they’re only flat text files, arrays or MySQL result sets.
By the end of this tutorial, I hope you’ll have an accurate idea of how to use a generic Iterator structure. I will show how it is useful for traversing different data structures by providing specific implementations for each of the abstract methods defined within the base Iterator class. So, let’s not waste any more time and start building different iterators in PHP!