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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top