I am trying to clone an \ArrayIterator object, but it seems like the cloned one is still referencing to the original one.
$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();
Anyone have explanation to this behavior? Thank you in advance.
Though I am having difficulty locating documentation that explicitly says so, internally
ArrayIterator's private$storageproperty wherein the array is held must be a reference to an array rather than the array itself directly stored within the object.The documentation on
clonesays thatSo when you
clonetheArrayIteratorobject, the newly cloned object contains a reference to the same array as the original one. Here is an old bug report wherein this behavior is said to be the expected behavior.If you want to copy the current state of an
ArrayIterator, you might consider instead instantiating a new one using the array returned bygetArrayCopy()The above is a simple operation though, and only creates a new
ArrayIteratorwith the currently stored array as the original. It does not maintain the current iteration state. To do that, you would need to also callseek()to advance the pointer to the desired position. Here is a thorough answer explaining how that could be done.