InternalIterator::key()

返回当前迭代器指向的元素的键名

首字母:I

函数名称:InternalIterator::key()

适用版本:PHP 5 >= 5.1.0, PHP 7

函数描述:该函数用于返回当前迭代器指向的元素的键名。

用法:

mixed InternalIterator::key ( void )

参数: 该函数不接受任何参数。

返回值: 返回当前迭代器指向的元素的键名。如果元素没有键名,则返回 null。

示例:

class MyIterator implements Iterator {
 private $position = 0;
 private $array = array(
 "firstElement",
 "secondElement",
 "thirdElement"
 );
 public function __construct() {
 $this->position = 0;
 }
 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: " . $key . ", Value: " . $value . "\n";
}

输出:

Key: 0, Value: firstElement
Key: 1, Value: secondElement
Key: 2, Value: thirdElement

在上面的示例中,我们创建了一个自定义的迭代器类 MyIterator,实现了 Iterator 接口的方法。在其中的 key() 方法中,我们返回了当前迭代器指向的元素的键名,即当前的位置。然后我们通过 foreach 循环遍历迭代器,并输出每个元素的键名和值。最终输出了每个元素的键名和值。

同首字母函数