简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM