Dan Lugg
Dan Lugg

Reputation: 20612

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.

Upvotes: 4

Views: 708

Answers (2)

nickb
nickb

Reputation: 59709

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.

Upvotes: 3

vstm
vstm

Reputation: 12537

Why not do something like that:

$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's not beautiful but it's at least concise.

Upvotes: 2

Related Questions