Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^188) CHAPTER 12 ■ SPL ARRAY OVERLOADING


Just the Facts


This chapter explained how to use objects as arrays. This is accomplished with the ArrayAccess
interface and the four defined methods: offsetSet(), offsetGet(), offsetExists(), and
offsetUnset(). The count() function can be interfaced through the Countable interface. This
interface defines a single method, count(), which must return an integer representing the number
of elements in a collection. Using the versatile ArrayObject class, you can create extensible
collections.
As an example, these concepts were combined to create an elegant shopping cart solu-
tion using these SPL interfaces. This solution allowed you to add elements to the collection
and also create methods on the collection, such as the ability to get a subtotal of all the items
in the shopping cart.
As an advanced use of the ArrayAccess interface, you can create an Object class that will let
you store complex objects as array keys.

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

Free download pdf