Search code examples
phpobjectsplkey-value-store

SplObjectStorage and sugary syntax in PHP


Quick one; I doubt it's possible, but is there any way to take advantage of the array($key => $value); syntax of PHP with regard to SplObjectStorage objects?

What I mean is, is there any such way to achieve:

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

In the context initializing an object store? As of the moment I'm simply using: (and will probably continue, considering the sheer unlikeliness of this being a possibility)

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

Would be nice, highly doubting it, but maybe someone knows better.


Solution

  • While it would be a more concise syntax, unfortunately it's not possible. The best you can do is either:

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

    or

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

    When adding object to an SplObjectStorage.