牛牛在线工具

InternalIterator::rewind()

收录 8868 个 PHP 函数,含用途说明与用法示例。

InternalIterator::rewind()

将迭代器的指针重置到第一个元素

函数名:InternalIterator::rewind() 函数描述:该方法用于将迭代器的指针重置到第一个元素。 适用版本:该方法适用于PHP 5以上的版本。 用法: void InternalIterator::rewind ( void ) 参数: 该方法没有参数。 返回值: 该方法没有返回值。 示例: 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; $it->rewind(); echo $it->current(); // 输出:first element 在上面的示例中,我们创建了一个自定义的迭代器类MyIterator,该类实现了Iterator接口。在rewind()方法中,我们将$position属性重置为0,以便将指针重置到第一个元素。然后,我们通过调用rewind()方法将迭代器的指针重置到第一个元素,并使用current()方法获取当前元素的值。最后,我们输出了第一个元素的值:"first element"。