25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Elements of Object-oriented Design ” 179<br />

class myData implements Iterator {<br />

private $myData = array(<br />

"foo",<br />

"bar",<br />

"baz",<br />

"bat");<br />

private $current = 0;<br />

function current() {<br />

return $this->myData[$this->current];<br />

}<br />

function next() {<br />

$this->current += 1;<br />

}<br />

function rewind() {<br />

$this->current = 0;<br />

}<br />

function key() {<br />

return $this->current;<br />

}<br />

function valid() {<br />

return isset($this->myData[$this->current]);<br />

}<br />

}<br />

$data = new myData();<br />

foreach ($data as $key => $value) {<br />

echo "$key: $value\n";<br />

}<br />

This example will iterate over each of the four elements in the myData private property<br />

in the exact same way foreach() works on a standard Array.<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

Seekable Iterators<br />

The next step up from a standard Iterator is the SeekableIterator, which extends<br />

the standard Iterator interface and adds a seek() method to enable the ability to<br />

retrieve a specific item from internal data store. Its interface looks like this:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!