ArrayAccess multidimensional (un)set?
Posted
by anomareh
on Stack Overflow
See other posts from Stack Overflow
or by anomareh
Published on 2010-05-21T10:59:42Z
Indexed on
2010/05/21
11:20 UTC
Read the original article
Hit count: 310
I have a class implementing ArrayAccess
and I'm trying to get it to work with a multidimensional array. exists
and get
work. set
and unset
are giving me a problem though.
class ArrayTest implements ArrayAccess {
private $_arr = array(
'test' => array(
'bar' => 1,
'baz' => 2
)
);
public function offsetExists($name) {
return isset($this->_arr[$name]);
}
public function offsetSet($name, $value) {
$this->_arr[$name] = $value;
}
public function offsetGet($name) {
return $this->_arr[$name];
}
public function offsetUnset($name) {
unset($this->_arr[$name]);
}
}
$arrTest = new ArrayTest();
isset($arrTest['test']['bar']); // Returns TRUE
echo $arrTest['test']['baz']; // Echo's 2
unset($arrTest['test']['bar']; // Error
$arrTest['test']['bar'] = 5; // Error
I know $_arr
could just be made public so you could access it directly, but for my implementation it's not desired and is private.
The last 2 lines throw an error: Notice: Indirect modification of overloaded element
.
I know ArrayAccess
just generally doesn't work with multidimensional arrays, but is there anyway around this or any somewhat clean implementation that will allow the desired functionality?
The best idea I could come up with is using a character as a separator and testing for it in set
and unset
and acting accordingly. Though this gets really ugly really fast if you're dealing with a variable depth.
Does anyone know why exists
and get
work so as to maybe copy over the functionality?
Thanks for any help anyone can offer.
© Stack Overflow or respective owner