Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^186) CHAPTER 12 ■ SPL ARRAY OVERLOADING
public function offsetExists($key) {
return array_key_exists(spl_object_hash($key), $this->_values);
}
public function offsetUnset($key) {
unset($this->_values[spl_object_hash($key)]);
unset($this->_keys[spl_object_hash($key)]);
}
}
$key = new KeyObject();
$collection = new CollectionObject();
$collection[$key] = 'test';
echo $collection[$key];
test
This collection works by storing the object’s hash code as the index. When you provide an
object to retrieve the value, it is hashed and used to look up the correct value.
To provide iteration support, you need to extend this class from ArrayIterator or imple-
ment the IteratorAggregate interface.
■Note At the time of writing, it is currently illegal in PHP to return an object from key() in the Iterator
interface. Because of this limitation, it is impossible to iterate this object returning object keys.
In addition to deriving your class from ArrayIterator, you will want to provide a method
to return an object key given an object hash. Listing 12-9 shows this collection in completed form.
Listing 12-9. Storing Complex Objects As Array Keys
class KeyObject {}
class CollectionObject extends ArrayIterator implements ArrayAccess {
protected $_keys, $_values;
public function __construct() {
$this->_keys = array();
$this->_values = array();
McArthur_819-9C12.fm Page 186 Thursday, February 28, 2008 7:51 AM

Free download pdf