Using SplObjectStorage as a data map, can you use a mutable array as 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] 1 , which is. I would also expect $storage[$fooB] be array('test') , which is not the case. It also triggers a notification that states: "Indirect modification of an overloaded SplObjectStorage element does not affect ..."

I think this is because the implementation of ArrayAccess in SplObjectStorage does not return a value by reference.

Is it possible to use SplObjectStorage as a data map, where keys are objects and values ​​are mutable arrays? Are there other viable options for doing this kind of work?

+6
source share
1 answer

Indirect modification (i.e. offsetGet return link) is a recent ability. See note for ArrayAccess::offsetGet . SplObjectStorage doesn't seem to be using it (yet?).

I suggest you use a direct modification instead:

 $a = $storage[$fooB]; $a[] = 'test'; $storage[$fooB] = $a; 
+6
source

Source: https://habr.com/ru/post/908990/


All Articles