Search code examples
phparraysarrayobject

Using ArrayObject to store arrays


I am trying to store an array and manipulate that array using a custom class that extends ArrayObject.

class MyArrayObject extends ArrayObject {
    protected $data = array();

    public function offsetGet($name) {
        return $this->data[$name];
    }

    public function offsetSet($name, $value) {
        $this->data[$name] = $value;
    }

    public function offsetExists($name) {
        return isset($this->data[$name]);
    }

    public function offsetUnset($name) {
        unset($this->data[$name]);
    }
}

The problem is if I do this:

$foo = new MyArrayObject();
$foo['blah'] = array('name' => 'bob');
$foo['blah']['name'] = 'fred';
echo $foo['blah']['name'];

The output is bob and not fred. Is there any way I can get this to work without changing the 4 lines above?


Solution

  • This is a known behaviour of ArrayAccess ("PHP Notice: Indirect modification of overloaded element of MyArrayObject has no effect" ...).

    http://php.net/manual/en/class.arrayaccess.php

    Implement this in MyArrayObject:

    public function offsetSet($offset, $data) {
        if (is_array($data)) $data = new self($data);
        if ($offset === null) {
            $this->data[] = $data;
        } else {
            $this->data[$offset] = $data;
        }
    }