【问题标题】:How to get the object associated with the current key while iterating through SplObjectStorage in PHP 5.4如何在 PHP 5.4 中迭代 SplObjectStorage 时获取与当前键关联的对象
【发布时间】:2014-02-18 19:01:07
【问题描述】:

在 PHP 5.4 中,我有一个 SplObjectStorage 实例,我在其中将对象与一些额外的元数据相关联。然后我需要遍历 SplObjectStorage 的实例并检索与当前键关联的对象。我尝试使用 SplObjectStorage::key 但这不起作用(但可能在 PHP 5.5 中有效)。

这是我正在尝试做的简化版本:

$storage = new SplObjectStorage;
$foo = (object)['foo' => 'bar'];
$storage->attach($foo, ['room' => 'bar'];

foreach ($storage as $value) {
    print_r($value->key());
}

我真正需要的是某种方法来检索与键关联的实际对象。据我所知,甚至无法手动创建具有数字索引和 SplObjectStorage 指向的对象的单独索引数组。

【问题讨论】:

标签: php spl


【解决方案1】:

这样做:

$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);
}

查看更多 SplObjectStorage::currentSplObjectStorage::getInfo

【讨论】:

  • 你确定吗?我被检查了:object(stdClass)#2 (1) { ["foo"]=> string(3) "bar" } array(1) { ["room"]=> string(3) "bar" }
  • 尝试添加另一个没有关联数据的对象 (foo1) - $assoc_key 将是 NULL
  • 显然 $storage->current() 返回用作键的对象, $storage->getInfo() 返回与其关联的数据。这对我来说并不明显,因为 Iterator::current() 通常返回与键关联的数据,反之亦然。
【解决方案2】:

SplObjectStorage 被创建时,Iterators 可以not return object-valued keys (后来修复了,但是因为 BC 的原因,SplObjectStorage 没有改变)。因此,使用 foreach 迭代 SplObjectStorage 将键作为值返回,您必须自己检索值,例如 this (play on 3v4l.org):

<?php
$spl = new SplObjectStorage ();

$keyForA = (object) ['key' => 'A'];
$keyForB = (object) ['key' => 'B'];

$spl[$keyForA] = 'value a';
$spl[$keyForB] = 'value b';

foreach ($spl as $i => $key) {
  $value = $spl[$key];

  print "Index: $i\n";
  print "Key: " . var_export($key, TRUE) . "\n";;
  print "Value: " . var_export($value, TRUE) . "\n";;
  print "\n";
}
?>

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2016-02-08
    • 2017-02-12
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多