Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the object associated with the current key while iterating through SplObjectStorage in PHP 5.4

Tags:

php

spl

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.

like image 483
Phillip Whelan Avatar asked Jan 27 '14 19:01

Phillip Whelan


1 Answers

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.

like image 167
voodoo417 Avatar answered Sep 20 '22 22:09

voodoo417