gpt4 book ai didi

php - 我如何在 PHP 中克隆 ArrayIterator?

转载 作者:可可西里 更新时间:2023-11-01 00:41:42 27 4
gpt4 key购买 nike

我正在尝试克隆一个\ArrayIterator 对象,但看起来克隆的对象仍在引用原始对象。

$list = new \ArrayIterator;
$list->append('a');
$list->append('b');

$list2 = clone $list;
$list2->append('c');
$list2->append('d');

// below result prints '4', i am expecting result '2'
echo $list->count();

有人对这种行为有解释吗?提前谢谢你。

最佳答案

虽然我很难找到明确说明的文档,但在内部 ArrayIterator 的私有(private) $storage 属性(其中保存数组)必须是对数组的引用,而不是而不是数组本身直接存储在对象中。

documentation on clone说是

PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

因此,当您克隆 ArrayIterator 对象时,新克隆的对象包含对与原始数组相同的数组的引用。 Here is an old bug report其中这种行为被称为预期行为。

如果您想复制 ArrayIterator 的当前状态,您可以考虑使用数组 returned by getArrayCopy() 来实例化一个新的。

$iter = new \ArrayIterator([1,2,3,4,5]);

// Copy out the array to instantiate a new one
$copy = new \ArrayIterator($iter->getArrayCopy());
// Modify it
$copy->append(6);

var_dump($iter); // unmodified
php > var_dump($iter);
class ArrayIterator#1 (1) {
private $storage =>
array(5) {
[0] =>
int(1)
[1] =>
int(2)
[2] =>
int(3)
[3] =>
int(4)
[4] =>
int(5)
}
}

var_dump($copy); // modified
class ArrayIterator#2 (1) {
private $storage =>
array(6) {
[0] =>
int(1)
[1] =>
int(2)
[2] =>
int(3)
[3] =>
int(4)
[4] =>
int(5)
[5] =>
int(6)
}
}

虽然上面是一个简单的操作,只是创建一个新的 ArrayIterator 以当前存储的数组作为原始数组。它维护当前的迭代状态。为此,您还需要调用 seek() 将指针前进到所需位置。 Here is a thorough answer explaining how that could be done .

关于php - 我如何在 PHP 中克隆 ArrayIterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34468244/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com