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.

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

}<br />

$this->array[$offset] = $value;<br />

function offsetGet ($offset) {<br />

return $this->array[$offset];<br />

}<br />

function offsetUnset ($offset) {<br />

unset ($this->array[$offset]);<br />

}<br />

function offsetExists ($offset) {<br />

return array_key_exists ($this->array, $offset);<br />

}<br />

}<br />

$obj = new myArray();<br />

$obj[1] = 2; // Works.<br />

$obj[’a’] = 1; // Throws exception.<br />

As you can see, this feature of SPL provides you with an enormous amount of control<br />

over one of <strong>PHP</strong>’s most powerful (and most useful) data types. Used properly,<br />

ArrayAccess is a great tool for building applications that encapsulate complex behaviours<br />

in a data type that everyone is used to.<br />

Simple Iteration<br />

The Iterator interface is the simplest of the iterator family, providing simple iteration<br />

over any single-dimension array. It looks like this:<br />

interface Iterator {}<br />

function current();<br />

function next();<br />

function rewind();<br />

function key();<br />

function valid();<br />

}<br />

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

You can see a simple implementation of the interface that allows iteration over a<br />

private property containing a simple array:

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

Saved successfully!

Ooh no, something went wrong!