Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Making Objects Behave Like Arrays

class MyArray implements ArrayAccess, Countable
  class MyArray implements ArrayAccess, Countable {
      private $_data = array();
      /* ArrayAccess interface */
      public function offsetSet($offset, $value) {
        $this->_data[$offset] = $value;
      public function offsetExists($offset) {
        return isset($this->_data[$offset]);
      public function offsetUnset($offset) {

      public function offsetGet($offset) {
        //return (isset($this->_data[$offset])) ? $this->_data[$offset] : null;
        return ($this->offsetExists($offset)) ? $this->_data[$offset] : null;
      /* Countable Interface */
      public function count() {
        return count($this->_data);
  $a = new MyArray();
  $a[0] = 'I';
  $a[1] = 'II';
  $a[2] = 'III';
  $a[3] = 'IV';
  for ($i = 0; $i < count($a); $i++) {
    printf('<p>%s</p>', htmlspecialchars($a[$i]));

Using an Object Like an Array with SPL (splArray.php)

SPL, the Standard PHP Library, is one of the most underrated features of PHP. It basically offers a huge set of interfaces. If you create a class using one of those interfaces, you might use standard PHP functions with your class. The documentation at http://php.net/spl is not always as detailed as you would expect, but it does give you some great pointers as to what is possible.

As a simple example, we will create a class (you can find more about various aspects of object-oriented programming [OOP] in Chapter 4) that implements two interfaces:

  • ArrayAccess—Allows accessing individual elements within the object’s collection (in our code, a simple array)
  • Countable—Allows calling count() on an object instance

If you want full array support, you need to implement additional interfaces, including Iterable (for iterator support; for example, via foreach) and some more. The ArrayObject interface aggregates several of the required interfaces, which in turn could even allow advanced features like user-defined sorting.

  • + Share This
  • 🔖 Save To Your Account