SplObjectStorage and sugary syntax in PHP

Quick; I doubt it is possible, but is there a way to use the syntax array($key => $value); PHP regarding SplObjectStorage objects?

I mean, is there such a way:

 $store = // ? new KeyObject() => new ValueObject(), new KeyObject() => new ValueObject(), // ... 

In the context of object store initialization? At the time I just use: (and will probably continue, given that there is a clear probability that this is possible)

 $store = new SplObjectStorage(); $store[new KeyObject()] = new ValueObject(); $store[new KeyObject()] = new ValueObject(); // ... 

It would be nice, I doubt it very much, but maybe someone knows better.

+4
source share
2 answers

Although this would be a more concise syntax, unfortunately this is not possible. The best you can do is either:

 $store[new KeyObject()] = new ValueObject(); 

or

 $store->append( new KeyObject(), new ValueObject()); 

When adding an object to SplObjectStorage .

+3
source

Why not do something like this:

 $store = new SplObjectStorage(); $data = array( array(new KeyObject, new ValueObject), array(new KeyObject, new ValueObject), array(new KeyObject, new ValueObject), ); foreach($data as $item) { list($key, $value) = $item; $store->attach($key, $value); } 

It is not beautiful, but it is at least brief.

+2
source

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


All Articles