Building an Iterator with PHP

Building an Iterator with PHP

Interface

An Iterator has a very simple, and at many times, clean interface.

<?php
function Iterator($array) // Constructor. Takes array to be traversed as a parameter.
function reset() // Sets internal pointer to the first element
function end() // Sets internal pointer to the last element
function seek($position) // Sets internal pointer to desired position
function next() // Returns next element in the iteration
function previous() // Returns previous element in the iteration
?>

With an interface like this, you can easily perform all your daily tasks. An example would be traversing arrays in any way you want and from any position you want. One advantage of using this approach against native PHP array functions is that you have one interface for all of your array tasks. You will not use the foreach() construct for one case, list-each combination in the other and the next() and prev() functions in third any more. Another advantage is that now you can easily set the position on any particular element and start traversing from there in any way you want. Here are few code examples:

<?php
// $array = ?. // initialize the array
$iterator = new Iterator($array);
// traverse the array
while ($elem = $iterator->next()) {
echo $elem;
}
// traverse array in reverse order
$iterator->end();
while ($elem = $iterator->previous()) {
echo $elem;
}
// traverse array from fifth element on
$iterator->seek(5);
while ($elem = $iterator->next()) {
echo $elem;
}
?>

“OK” you say, “this is all nice but there is nothing I can’t do with a combination of native PHP functions”.

Besides the fact that you are accessing all your arrays through a unique interface. Another and the most important advantage is that the Iterator’s object structure allows you to easily expand its functionality.

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.