WHAT'S HOT
Prev | Current Page 371 | Next

Rob Allen, Nick Lo, and Steven Brown

"Zend Framework in Action"

Other type of objects may require
this though and for these cases, the ArrayAccess Interface is used.
17.2.2 Array Access and Countable
The ArrayAccess iterator allows a class to behave like an array. This means that a user of the class can
randomly access any element within the collection using the [] notation like this:
$element = $objectArray[4];
In a similar manner to Iterator, this is achieved using a set of functions that must be implemented by the
class. In this case the functions are: offsetExists(), offsetGet(), offsetSet() and offsetUnset(). The names are
self-explanatory and, as shown in listing 17.13, allow for the following array operations to be carried out:
Listing 17.13 Array operations with an ArrayAccess capable class
if(isset($rob['firstName']) { A
echo $rob['firstName']; B
$rob['firstName'] = 'R.'; C
}
unset($rob['firstName']); D
A calls offsetExists()
B calls offsetGet()
C calls offsetSet()
D calls offsetUnset()
The only other array based functionality that is useful to implement in the context of an object is the
count() function. This is done via the Countable interface which contains just one method, count(). As you
would expect, this function needs to return the number of items in the collection and then we have all the tools
to make a class behave like an array.


Pages:
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
Leona Lewis akcesoria motocyklowe betsson Paula Abdul Powermed