Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 785
Joe Lencioni Avatar asked Feb 21 '12 15:02

Joe Lencioni


1 Answers

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;
like image 181
Francis Avila Avatar answered Oct 14 '22 20:10

Francis Avila