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 ” 177<br />

• Simple Iteration<br />

• Seekable Iteration<br />

• Recursive Iteration<br />

• Filtered Iteration<br />

Accessing Objects as Arrays<br />

The ArrayAccess interface can be used to provide a means for your object to expose<br />

themselves as pseudo-arrays to <strong>PHP</strong>:<br />

interface ArrayAccess {<br />

function offsetSet($offset, $value);<br />

function offsetGet($offset);<br />

function offsetUnset($offset);<br />

function offsetExists($offset);<br />

}<br />

This interface provides the basic methods required by <strong>PHP</strong> to interact with an array:<br />

• offsetSet() sets a value in the array<br />

• offsetGet() retrieves a value from the array<br />

• offsetUnset() removes a value from the array<br />

• offsetExists() determines whether an element exists<br />

As a very quick example, consider the following class, which “emulates” an array that<br />

only accepts elements with numeric keys:<br />

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

class myArray implements ArrayAccess {<br />

protected $array = array();<br />

function offsetSet ($offset, $value) {<br />

if (!is_numeric ($offset)) {<br />

throw new Exception ("Invalid key $offset");<br />

}

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

Saved successfully!

Ooh no, something went wrong!