In PHP 5.4 I have an instance of SplObjectStorage where I associate objects with some extra metadata. I need to then iterate through the instance of SplObjectStorage and retrieve the object associated with the current key. I attempted to use SplObjectStorage::key but that did not work (but may work in PHP 5.5).
Here is a simplified version of what I am attempting to do:
$storage = new SplObjectStorage;
$foo = (object)['foo' => 'bar'];
$storage->attach($foo, ['room' => 'bar'];
foreach ($storage as $value) {
print_r($value->key());
}
All I really need is some way to retrieve the actual object that is associated with the key. It is not even possible to manually create a separate indexed array with the numeric index and the object SplObjectStorage points to, as far as I can tell.
Do it:
$storage = new SplObjectStorage;
$foo = (object)['foo' => 'bar'];
$storage->attach($foo, ['room' => 'bar']);
foreach ($storage as $value) {
$obj = $storage->current(); // current object
$assoc_key = $storage->getInfo(); // return, if exists, associated with cur. obj. data; else NULL
var_dump($obj);
var_dump($assoc_key);
}
See more SplObjectStorage::current and SplObjectStorage::getInfo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With