News Archive
PhpRiot Newsletter
Your Email Address:

More information

ArrayAccess vs ArrayObject

Note: This article was originally published at Planet PHP on 16 September 2011.
Planet PHP

I help people qualify for Zend Certification and in the last few months I've had questions about both ArrayAccess and ArrayObject. This post is an attempt to illuminate both.

In very simple terms, ArrayAccess is an interface, which you can implement in your own objects; ArrayObject, on the other hand, is a class, which you can either use or extend.


ArrayAccess is an interface built in to PHP which lets you dictate how PHP behaves when an object has array syntax (square brackets) attached to it. Interfaces are collections of function prototypes that we can use as templates for our own code. If you read the manual page for ArrayAccess, it shows four functions:

ArrayAccess { /* Methods */ abstract public boolean offsetExists (mixed $offset) abstract public mixed offsetGet (mixed $offset) abstract public void offsetSet (mixed $offset, mixed $value) abstract public void offsetUnset (mixed $offset) }

To implement this interface, we just declare all these methods in our class. Here is an example class:

class PrettyBasket implements ArrayAccess { protected $contents = array(); public function offsetExists($index) { return isset($this-contents[$index]); } public function offsetGet($index) { if($this-offsetExists($index)) { return $this-contents[$index]; } return false; } public function offsetSet($index, $value) { if($index) { $this-contents[$index] = $value; } else { $this-contents["/

Truncated by Planet PHP, read more at the original (another 5471 bytes)