EmptyIterator::valid()

判断当前迭代器指针位置是否有效

首字母:E

函数名:EmptyIterator::valid()

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

用法:此方法用于判断当前迭代器指针位置是否有效。如果有效,则返回true,否则返回false。

示例:

class MyIterator extends EmptyIterator {
 public function valid() {
 // 自定义的valid方法
 return ($this->key() < 3);
 }
 public function current() {
 // 自定义的current方法
 return "Current value: " . $this->key();
 }
 public function key() {
 // 自定义的key方法
 return $this->position();
 }
 public function next() {
 // 自定义的next方法
 $this->position++;
 }
 public function rewind() {
 // 自定义的rewind方法
 $this->position = 0;
 }
}
$iterator = new MyIterator();
foreach ($iterator as $key => $value) {
 echo "Key: " . $key . ", Value: " . $value . "\n";
 echo "Is Valid: " . ($iterator->valid() ? 'true' : 'false') . "\n";
}

输出:

Key: 0, Value: Current value: 0
Is Valid: true
Key: 1, Value: Current value: 1
Is Valid: true
Key: 2, Value: Current value: 2
Is Valid: true

同首字母函数