Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 12 ■ SPL ARRAY OVERLOADING^185

The SPL has a solution to this problem. In Chapter 9, you were introduced to the spl_object_
hash() function. This function creates a unique identifier for any object instance and can
allow you to store an object hash as a key in an array. Listing 12-7 shows an example of using
spl_object_hash().

Listing 12-7. Using spl_object_hash to Store Objects As Array Keys

class MyObject {}

$a = new MyObject();
$b = array(spl_object_hash($a)=>'Test');

echo $b[spl_object_hash($a)];

Test

So that works, but it’s not very convenient. You can do better with the ArrayAccess inter-
face by making it do the object hashing for you. You will need to create two classes: a KeyObject
class, which will serve as the object that will be stored in the key, and a CollectionObject class,
which has custom ArrayAccess interface methods and will serve as your array. The customized
ArrayAccess methods shown in Listing 12-8 will handle the hashing of the key and storing the
objects within it.

Listing 12-8. An Object-Keyed Collection

class KeyObject {}

class CollectionObject implements ArrayAccess {

protected $_keys, $_values;

public function __construct() {
$this->_keys = array();
$this->_values = array();
}

public function offsetSet($key, $value) {
$this->_keys[spl_object_hash($key)] = $key;
$this->_values[spl_object_hash($key)] = $value;
}

public function offsetGet($key) {
return $this->_values[spl_object_hash($key)];
}

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

Free download pdf