首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[函数]Iterator::rewind()函数—用法及示例

发布于 2025-04-28 16:40:09
0
25

函数名:Iterator::rewind()

函数说明:Iterator::rewind() 方法将迭代器重置到第一个元素。

适用版本:该函数在PHP 5 及以上版本中可用。

用法示例:

<?php
class MyIterator implements Iterator {
    private $position = 0;
    private $array = array(
        "first element",
        "second element",
        "third element",
    );

    public function rewind() {
        $this->position = 0;
    }

    public function current() {
        return $this->array[$this->position];
    }

    public function key() {
        return $this->position;
    }

    public function next() {
        ++$this->position;
    }

    public function valid() {
        return isset($this->array[$this->position]);
    }
}

$it = new MyIterator();

// 使用rewind()方法将迭代器重置到第一个元素
$it->rewind();

while($it->valid()) {
    echo $it->key() . ' => ' . $it->current() . "\n";
    $it->next();
}
?>

输出结果:

0 => first element
1 => second element
2 => third element

在上述示例中,我们创建了一个自定义的迭代器类MyIterator,实现了Iterator接口的所有方法。在rewind()方法中,我们将迭代器的位置重置为0,使其指向第一个元素。然后,在while循环中,使用valid()方法检查迭代器是否还有下一个元素,如果有,则输出当前元素的键和值,并通过next()方法将迭代器移动到下一个元素。最终,输出了所有元素的键值对。

评论
一个月内的热帖推荐
啊龙
Lv.1普通用户

9545

帖子

31

小组

3242

积分

赞助商广告
站长交流