函數(shù)名:SeekableIterator::seek()
適用版本:PHP 5 >= 5.1.0, PHP 7
用法:該函數(shù)用于在SeekableIterator迭代器中定位到指定位置。它將迭代器的內(nèi)部指針移動(dòng)到指定的位置。
語法:bool SeekableIterator::seek ( int $position )
參數(shù):
- position:要定位的位置,必須是一個(gè)整數(shù)。
返回值:如果成功定位到指定位置,則返回true,否則返回false。
示例:
class MyIterator implements SeekableIterator {
private $data = array('A', 'B', 'C', 'D', 'E');
private $position = 0;
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->data[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->data[$this->position]);
}
public function seek($position) {
if (!isset($this->data[$position])) {
throw new OutOfBoundsException("Invalid position");
}
$this->position = $position;
}
}
$iterator = new MyIterator();
$iterator->seek(2); // 定位到位置2
echo $iterator->current(); // 輸出C
echo $iterator->key(); // 輸出2
$iterator->seek(4); // 定位到位置4
echo $iterator->current(); // 輸出E
echo $iterator->key(); // 輸出4
以上示例中,我們定義了一個(gè)實(shí)現(xiàn)了SeekableIterator接口的自定義迭代器類MyIterator。在該類中,我們實(shí)現(xiàn)了必要的方法,包括seek()方法。在示例中,我們創(chuàng)建了一個(gè)MyIterator對(duì)象,并使用seek()方法來定位到指定位置。然后,我們通過current()方法輸出當(dāng)前位置的值,通過key()方法輸出當(dāng)前位置的鍵。