PHPBuilder - PHP Iterator



RSS Twitter
Articles Application Architecture

PHP Iterator

by: Dejan Bosanac
|
February 25, 2003

PHP arrays are generally a very powerful object container. But still, we can easily add a little more fuel to them. Imagine an iterator object as a kind of wrapper around our arrays. What we will try to accomplish here is to create unique interface for traversing arrays and to add a little more control over how our objects are created and finally, to support lazy loading.

Interface

Iterator has a very simple and many times seen 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 the interface like this you can easily perform all your daily tasks (such as 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 foreach() construct in one case, list-each combination in other and yet next() and prev() functions in third any more. One more advantage is that now you can easily 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;
}
?>

1
|
2
|
3
|
4
|
5
|
6
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Dejan Bosanac

Comment:



Comment:

(Maximum characters: 1200). You have characters left.