Search code examples
phparrayobjectarrayaccess

Multidimensional ArrayObject


Is there a way to implement class with multidimensional array access? I want something like

$obj = new MultiArrayObject();
$obj['key']['subkey'] = 'test';
echo $obj['key']['subkey']; //expect 'test' here

Solution

  • There is no syntax with which a class can intercept multiple levels of array access, but you can do it one level at a time by implementing the ArrayAccess interface:

    class MultiArrayObject implements ArrayAccess {
    
        protected $data = [];
    
        public function offsetGet($offset) {
            if (!array_key_exists($offset, $this->data)) {
                $this->data[$offset] = new $this;
            }
            return $this->data[$offset];
        }
    
        /* the rest of the ArrayAccess methods ... */
    
    }
    

    This would create and return a new nested MultiArrayObject as soon as you access $obj['key'], on which you can set data.

    However, this won't allow you to distinguish between setters and getters; all values will always be implicitly created as soon as you access them, which might make the behaviour of this object a little weird.