179
■ ■ ■
CHAPTER 12
SPL Array Overloading
Array overloading is the process of using an object as an array. Some people coming from
different language backgrounds may know this ability by another name: indexers.
The material in this chapter will help you learn how to create objects that can have their
contents read and manipulated using the standard array syntax.
Introducing ArrayAccess
The ArrayAccess interface enables your objects to behave as arrays. It consists of four methods,
as listed in Table 12-1.
The code in Listing 12-1 shows a very simple form of implementing the ArrayAccess interface,
and it is not even iterable. However, it does demonstrate how the array machinery works.
Listing 12-1. Using ArrayAccess
class MyArray implements ArrayAccess {
protected $_arr;
public function __construct() {
$this->_arr = array();
}
Table 12-1. ArrayAccess Methods
Method Description
offsetSet() Sets an offset for array access. Takes two parameters: an offset to be used as
the array index and a value to assign.
offsetGet() Gets the associated value given a specified offset.
offsetExists() Returns a Boolean value for a given offset to indicate whether (true) or not
(false) a specific key has a value that may be fetched with offsetGet().
offsetUnset() Removes an item from the collection. It is called when you use the unset
statement or set an offset to null.
McArthur_819-9C12.fm Page 179 Thursday, February 28, 2008 7:51 AM