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

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

发布于 2025-04-28 12:40:41
0
23

函数名:InternalIterator::rewind() 函数描述:该方法用于将迭代器的指针重置到第一个元素。 适用版本:该方法适用于PHP 5以上的版本。 用法: void InternalIt...

函数名: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"。

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

9545

帖子

31

小组

3242

积分

赞助商广告
站长交流