略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: NoRewindIterator

2024-11-13

The NoRewindIterator class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

This iterator ignores rewind operations. This allows processing an iterator in multiple partial foreach loops.

类摘要

class NoRewindIterator extends IteratorIterator {
/* 方法 */
public __construct(Iterator $iterator)
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
/* 继承的方法 */
public IteratorIterator::next(): void
}

目录

add a noteadd a note

User Contributed Notes 1 note

up
5
Anonymous
2 years ago
As its name implies, NoRewindIterator doesn't invoke the "rewind" method when It reaches the end of the iterator.

Let's demonstrate it by two examles.

In this example the "rewind" method will be invoked after when the "foreache" reaches its end, so, we can repeat printing the same values as many times as we want:

<?PHP
$iterator
= new ArrayIterator(['PHP', 'Python', 'Go']);

foreach (
$iterator as $item) {
    echo
$item.PHP_EOL;
}

foreach (
$iterator as $item) {
    echo
$item.PHP_EOL;
}
?>

By using the NoRewindIterator, the "rewind" won't be invoked, so, we can't do as we did in previous example:

<?PHP
$iterator
= new ArrayIterator(['PHP', 'Python', 'Go']);
$iterator = new NoRewindIterator($iterator);

foreach (
$iterator as $item) {
    echo
$item.PHP_EOL;
}

// doesn't do anything
foreach ($iterator as $item) {
    echo
$item.PHP_EOL;
}

?>

官方地址:https://www.php.net/manual/en/class.norewinditerator.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3