In the following code:
$storage = new \SplObjectStorage();
$fooA = new \StdClass();
$fooB = new \StdClass();
$storage[$fooA] = 1;
$storage[$fooB] = array();
$storage[$fooA] = 2;
$storage[$fooB][] = 'test';
I would expect $storage[$fooA]
to be 1
, which it is. I would also expect $storage[$fooB]
to be array('test')
, which it is not. This also triggers a notice that reads, "Indirect modification of overloaded element of SplObjectStorage has no effect in..."
I think this happens because the implementation of ArrayAccess
in SplObjectStorage
doesn't return values by reference.
Is there any way to use SplObjectStorage
as a data map where keys are objects and values are mutable arrays? Are there any other viable options for doing this kind of work?
Indirect modification (i.e. offsetGet
returning a reference) is a recent ability. See the note for ArrayAccess::offsetGet
. It doesn't seem that SplObjectStorage makes use of it (yet?).
I suggest you use direct modification instead:
$a = $storage[$fooB];
$a[] = 'test';
$storage[$fooB] = $a;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With