HomePHP Page 3 - Iterators in the Simplest Sense: Traversing Different Data Structures
Building a concrete example: using the “FileIterator” class - PHP
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.
In order to illustrate the functionality of the “FileIterator” class I built previously, first I’ll create a simple text file, populated with some basic data. Then I will instantiate an object from the corresponding class, so I’m able to use its methods. First of all, here’s the basic “test.txt” text file:
This is the data for line 1 This is the data for line 2 This is the data for line 3 This is the data for line 4 This is the data for line 5 This is the data for line 6 This is the data for line 7 This is the data for line 8 This is the data for line 9 This is the data for line 10
And next, you can see the PHP script that traverses the above text file:
// instantiate 'FileIterator' object $fIterator=&new FileIterator('test.txt'); // display first line of file echo $fIterator->reset(); // display current line of file echo $fIterator->current(); // display next line of file echo $fIterator->next(); // display final line of file echo $fIterator->end(); // display previous line of file echo $fIterator->prev(); // seek a line within file echo $fIterator->seek(2); // count number of lines in file echo $fIterator->count();
The above snippet might seem like a trivial example, but in fact it’s demonstrating the ease of traversing a particular text file. Of course, here I populated the sample flat file with basic data, but think about the possible implementations for this “FileIterator” class, where file data has to be accessed either in a linear or random mode. Without a doubt, this class can be pretty helpful within a PHP application, particularly considering its ease and understandable source code.
Right, now you saw how simple it is to build a “FileIterator” class, by utilizing as a base class the pertinent array iterator you learned before. However, there are still more examples to show you, in order to continue demonstrating the versatility of iterators in PHP.
For this reason, in the next few lines I’ll define a result set iterator class, which comes in very handy for traversing MySQL data sets. Curious about how this is achieved? Fine, keep on reading to learn more.