【问题标题】:Using SplObjectStorage as a data map, can you use a mutable array as the data?使用 SplObjectStorage 作为数据映射,可以使用可变数组作为数据吗?
【发布时间】:2012-03-11 22:23:21
【问题描述】:

在以下代码中:

$storage = new \SplObjectStorage();

$fooA = new \StdClass();
$fooB = new \StdClass();

$storage[$fooA] = 1;
$storage[$fooB] = array();

$storage[$fooA] = 2;
$storage[$fooB][] = 'test';

我希望$storage[$fooA]1,它是。我还希望$storage[$fooB]array('test'),但事实并非如此。这也会触发一条通知,上面写着“间接修改 SplObjectStorage 的重载元素对...没有影响”

我认为这是因为SplObjectStorage 中的ArrayAccess 的实现没有通过引用返回值。

有没有办法使用SplObjectStorage 作为键是对象而值是可变数组的数据映射?有没有其他可行的选择来做这种工作?

【问题讨论】:

    标签: php spl arrayaccess splobjectstorage


    【解决方案1】:

    间接修改(即offsetGet 返回引用)是最近的一项功能。见the note for ArrayAccess::offsetGet。 SplObjectStorage 似乎没有使用它(还没有?)。

    我建议你改用直接修改:

    $a = $storage[$fooB];
    $a[] = 'test';
    $storage[$fooB] = $a;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2012-12-03
      • 2022-07-18
      • 2011-04-18
      相关资源
      最近更新 更多