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.
offsetSet() here?$this->data[$offset] = $value;...!?
Arraybehaves. What are you trying to do?Sessionclass, that will put data to Redis storage and will get it from there. Just like usual$_SESSIONvariable, but with additional features likesession_start()calls.ArrayObjectdoes exactly as you ask with multi-dimensional arrays without any extra coding. Maybe interesting? PHP ArrayAccess set multidimensional. I suspect thatArrayObjecthas access to a lot of the 'internal PHP array stuff' and provides it for free?