Using SplObjectStorage as a data map, can you use a mutable array as the data?
Asked Answered
U

1

6

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?

Unreflective answered 21/2, 2012 at 15:41 Comment(0)
G
6

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;
Goosegog answered 21/2, 2012 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.