HomePHP Page 3 - Iterators in the Simplest Sense: An Accessible Implementation in PHP 4
Building in an Iterator in PHP 4: setting up a functional example - PHP
In this first article of a series, Alejandro Gervasio explains the core concepts of Iterators in PHP, concentrating most of his efforts on the subject’s practical side.
One of the best things about PHP is that once the subjacent theory has been understood, translating it into functional code is really simple. This is precisely the case with Iterators, which, as you’ll see soon, are actually simple to code. In order to supply an illustrative example of how to write a working Iterator in PHP 4, what I’ll do next is define an abstract “Iterator” class that has some of the abstract methods I discussed earlier, useful for iterating over a generic data structure. Here’s the source code for this class:
// base abstract 'Iterator' class class Iterator{ function Iterator(){ if(get_class($this)=='Iterator'||!is_subclass_of ($this,'Iterator')){ trigger_error('This class is abstract. It cannot be instantiated!',E_USER_ERROR); } } // abstract 'current()' method function current(){} // abstract 'prev()' method function prev(){} // abstract 'next()' method function next(){} // abstract 'end' method function end(){} // abstract 'reset()' method function reset(){} // abstract 'seek()' method function seek(){} // abstract 'count()' method function count(){} }
That’s it. I told you it was really easy! As you can see, I defined the above class in such a way that it exposes a few methods for traversing a data structure of any type. Also, I defined this class as abstract, by including a checking block inside the constructor. This prevents the class from being instantiated, either when directly called within client code, or when invoked from inside a non-subclass.
Essentially, this sample “Iterator” class has seven different methods for iterating and processing data. It’s clear to see that each of them are extremely intuitive and understandable. Although none of these methods exposes a concrete implementation within the corresponding class, their names are suggestive enough to indicate what they’ll do when they're concretely defined.
In accordance with the concepts I explained above, the “reset()”, “prev()”, “current()”, “next()” and “end()” methods should be defined within the pertinent subclasses, so they must provide an easy way to move back and forth across a particular data structure. In a similar fashion, the “seek()” and count()” method should be defined in order to allow the seeking of a specific element, and the counting of the number of elements that comprise the structure itself.
Okay, at this point you know how a generic Iterator looks. Now, it’s time to do something useful with this powerful structure, so it can be used within a PHP application. Want to learn how to build an array Iterator, using the base class you just learned? Go ahead and read the next section.