0

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
3
  • This is how the default Array behaves. What are you trying to do? Commented Oct 2, 2015 at 13:35
  • I want to implement Session class, that will put data to Redis storage and will get it from there. Just like usual $_SESSION variable, but with additional features like session_start() calls. Commented Oct 2, 2015 at 13:50
  • ArrayObject does exactly as you ask with multi-dimensional arrays without any extra coding. Maybe interesting? PHP ArrayAccess set multidimensional. I suspect that ArrayObject has access to a lot of the 'internal PHP array stuff' and provides it for free? Commented Oct 2, 2015 at 21:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How to implement offsetSet() here?
$this->data[$offset] = $value;...!?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.