An iterator has a current position and advances only when traversal is requested.
What Is NoRewindIterator::rewind in PHP?
Restarts traversal when supported by the wrapped iterator.
NoRewindIterator::rewind()
This operation does not accept method arguments.
Example 1: Understanding the Basic Behavior
<?php
$iterator = new NoRewindIterator(new ArrayIterator(["north"=>10,"south"=>20,"west"=>30]));
$iterator->rewind();
var_dump($iterator->current());
Output:
int(10)
Explanation: Restarts traversal when supported by the wrapped iterator.
Example 2: Testing Another Case
<?php
$iterator = new NoRewindIterator(new ArrayIterator(["apple","pear","plum"]));
$iterator->rewind();
var_dump($iterator->current());
Output:
string(5) "apple"
Explanation: Rewinding is not supported equally by every Traversable source, especially consumed generators.
Practical Example: Applying the Operation
<?php
$iterator = new NoRewindIterator(new ArrayIterator(["red"=>"ready","blue"=>"waiting","green"=>"done"]));
$iterator->rewind();
var_dump($iterator->current());
Output:
string(5) "ready"
Explanation: Most iterator methods depend on cursor position, and behavior after exhaustion depends on the underlying iterator.
Important Behavior and Edge Cases
- Rewinding is not supported equally by every Traversable source, especially consumed generators.
- Most iterator methods depend on cursor position, and behavior after exhaustion depends on the underlying iterator.
Comparison With Related Approaches
| Approach | When to Use It |
|---|---|
NoRewindIterator::rewind | Restarts traversal when supported by the wrapped iterator. |
ArrayIterator | ArrayIterator wraps an array; iterator decorators can modify traversal without copying the source values. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Assuming every wrapped iterator can restart, even after a generator has advanced. | Rewinding is not supported equally by every Traversable source, especially consumed generators. |
| Choosing ArrayIterator without checking whether it provides the same result. | ArrayIterator wraps an array; iterator decorators can modify traversal without copying the source values. |
Key Takeaways
- Restarts traversal when supported by the wrapped iterator.
- Rewinding is not supported equally by every Traversable source, especially consumed generators.
- Most iterator methods depend on cursor position, and behavior after exhaustion depends on the underlying iterator.
The examples demonstrate where NoRewindIterator::rewind fits within traversable collections. Verify the relevant preconditions whenever you adapt the code to real data.