函數(shù)名稱:InternalIterator::current()
適用版本:PHP 5 >= 5.5.0, PHP 7
函數(shù)描述:此方法用于返回內(nèi)部迭代器中當(dāng)前指向的元素。
用法:
mixed InternalIterator::current ( void )
參數(shù):此函數(shù)不接受任何參數(shù)。
返回值:返回當(dāng)前指向的元素。如果沒有更多元素可供遍歷,則返回 FALSE。
示例:
class MyIterator implements Iterator {
private $position = 0;
private $array = array(
"firstElement",
"secondElement",
"thirdElement"
);
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;
foreach($it as $key => $value) {
echo $key . ": " . $value . "\n";
}
輸出:
0: firstElement
1: secondElement
2: thirdElement
在上面的示例中,我們創(chuàng)建了一個自定義的迭代器類 MyIterator
并實(shí)現(xiàn)了 Iterator
接口的方法。其中,current()
方法返回當(dāng)前指向的元素。我們使用 foreach
循環(huán)遍歷迭代器對象,并輸出每個元素的鍵和值。