Does SplMinHeap or SplMaxHeap implement Traversable interface logically?

Viewed 69

I noticed that SplMinHeap or SplMaxHeap implements the Iterator interface, which implements Traversable interface, so I can use iterator_to_array (Traversable $iterator) : array or foreach syntax to iterate any instance of these two classes.

SplMaxHeap extends SplHeap implements Iterator , Countable {

SplMinHeap extends SplHeap implements Iterator , Countable {

But when I iterate an instance of SplMinHeap/SplMaxHeap repeatedly, I got an empty array after the first iteration. It looks like that the first iteration broke the inner structure of SplMinHeap/SplMaxHeap.

<?php
$minHeap = new SplMinHeap();
$minHeap->insert(15);
$minHeap->insert(5);
$minHeap->insert(10);

foreach ($minHeap as $val) echo $val, PHP_EOL;

var_dump(iterator_to_array($minHeap));  // empty array
var_dump(iterator_to_array($minHeap));  // empty array

Yes, we can traverse/iterate this data structure as its class declared, but only once. Is it logical?

0 Answers
Related