PHP Conference Japan 2024

SeekableIterator 介面

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

簡介

可搜尋的迭代器。

介面概要

interface SeekableIterator extends Iterator {
/* 方法 */
public seek(int $offset): void
/* 繼承的方法 */
}

範例

範例 #1 基本用法

此範例示範如何建立一個自訂的 SeekableIterator,搜尋到一個位置並處理無效位置。

<?php
class MySeekableIterator implements SeekableIterator {

private
$position;

private
$array = array(
"first element",
"second element",
"third element",
"fourth element"
);

/* Method required for SeekableIterator interface */

public function seek($position) {
if (!isset(
$this->array[$position])) {
throw new
OutOfBoundsException("invalid seek position ($position)");
}

$this->position = $position;
}

/* Methods required for Iterator interface */

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]);
}
}

try {

$it = new MySeekableIterator;
echo
$it->current(), "\n";

$it->seek(2);
echo
$it->current(), "\n";

$it->seek(1);
echo
$it->current(), "\n";

$it->seek(10);

} catch (
OutOfBoundsException $e) {
echo
$e->getMessage();
}
?>

上述範例將輸出類似以下的內容

first element
third element
second element
invalid seek position (10)

目錄

新增註記

使用者貢獻的註記 4 則註記

svenr at selfhtml dot org
13 年前
最佳方法

<?php

if ($object instanceof SeekableIterator) {
echo
"$object 具有 seek() 方法";
}

?>

請利用檢查是否已實作特定介面,以確保您正在處理的物件確實具有您即將使用的方法。

這也可以作為類型提示

<?php

class foo {
public function
doSomeSeeking(SeekableIterator $seekMe) {
$seekMe->seek(10); // 將會正常運作,否則類型提示會觸發錯誤
}
}

?>
info at ensostudio dot ru
2 年前
注意:SeekableIterator::seek() 的 $offset 參數是列表中的位置,而不是陣列鍵值。
<?php
$iterator
= new ArrayIterator([1 => "apple", 2 => "banana", 3 => "cherry"]);
echo
$iterator->offsetGet(2); // banana
$iterator->seek(2);
echo
$iterator->current(); // cherry
?>
info at ensostudio dot ru
4 年前
注意:使用 array_key_exists 取代 isset!
<?php
public function seek($position)
{
$position = (int) $position;
if (!
array_key_exists($position, array_values($this->array))) {
throw new
OutOfBoundsException('Invalid position to seek: ' . $position);
}
$this->position = $position;
}
?>
匿名
11 年前
上面的程式碼缺少一個右括號。

<?php
if (!isset($this->array[$position]) {
throw new
OutOfBoundsException("invalid seek position ($position)");
}
?>

應該是

<?php
if (!isset($this->array[$position])) { // 在此處加上右括號
throw new OutOfBoundsException("invalid seek position ($position)");
}
?>
To Top