Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^180) CHAPTER 12 ■ SPL ARRAY OVERLOADING
public function offsetSet($offset, $value) {
$this->_arr[$offset] = $value;
}
public function offsetGet($offset) {
return $this->_arr[$offset];
}
public function offsetExists($offset) {
return array_key_exists($offset, $this->_arr);
}
public function offsetUnset($offset) {
unset($this->_arr[$offset]);
}
}
$myArray = new MyArray(); // Create an object as an array
$myArray['first'] = 'test'; // offsetSet, set data by key
$demo = $myArray['first']; // offsetGet, get data by key
unset($myArray['first']); // offsetUnset, remove key
ArrayAccess is provided primarily because not all collections are based on a real array.
Collections using the ArrayAccess interface may instead broker requests to a service-oriented
architecture (SOA) back-end, or any other form of disconnected storage. This allows you to
defer materialization of your underlying data until it is actually accessed.
However, for the vast majority of cases, you will likely use an array as the underlying repre-
sentation. Then you will add methods to this class to work with this data. For this purpose,
there is the built-in ArrayObject class, discussed next.
The ArrayAccess interface itself does not provide the ability to count the number of elements
in the array. This is because not all ArrayAccess classes have a finite length. Those that do, however,
can—and probably should—implement the Countable interface. This interface is extremely
simple, containing only one method, count(), to return the number of elements.


Introducing ArrayObject


The ArrayObject class is an ArrayAccess implementer that also gives you iteration support, as
well as quite a few useful methods for sorting and working with data, as listed in Table 12-2.
ArrayObject also implements Countable for you. It is based on an Array internally, so it is limited to
working with real, fully populated data, but it can serve as a useful base class for your applications.
Listing 12-2 demonstrates using ArrayObject.

McArthur_819-9C12.fm Page 180 Thursday, February 28, 2008 7:51 AM

Free download pdf