牛牛在线工具

Iterator::current()

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

Iterator::current()

返回迭代器中当前指向的元素的值

函数名称:Iterator::current() 函数描述:返回迭代器中当前指向的元素的值。 适用版本:PHP 5, PHP 7 用法: mixed Iterator::current ( void ) 参数: 该函数没有参数。 返回值: 返回当前迭代器指向的元素的值。如果没有更多元素可供迭代,则返回 false。 示例: 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(); while ($it->valid()) { echo $it->current() . "\n"; $it->next(); } 输出: first element second element third element 在这个示例中,我们创建了一个实现了 Iterator 接口的自定义迭代器类 MyIterator。该类中的 current() 方法返回当前位置的元素的值。我们使用该自定义迭代器来遍历一个包含三个元素的数组,并输出每个元素的值。