PHPのIteratorインターフェースを継承すると、foreach文でループできるクラスを作成することができます。
実装しなければならないメソッドは次の5つです。
//現在の要素を返す
public mixed current ( void )
//現在の要素のキーを返す
public scalar key ( void )
//次の要素に進む
public void next ( void )
//イテレータの最初の要素に巻き戻す
public void rewind ( void )
//現在位置が有効かどうかを調べる
public boolean valid ( void )
次のサンプルコードは、10から20までの整数を返すクラスです。
<?php
/**
* 指定した範囲の整数を返すクラス
*/
class RangeIterator implements Iterator {
private $from; //最初の数
private $to; //最後の数
private $index = 0; //現在位置
public function __construct($from, $to)
{
$this->from = $from;
$this->to = $to;
}
/**
* 現在の要素を返す
*/
public function current() {
return $this->from + $this->index;
}
/**
* 現在の要素のキーを返す
*/
public function key() {
return $this->index;
}
/**
* 次の要素に進む
*/
public function next() {
$this->index++;
}
/**
* イテレータの最初の要素に巻き戻す
*/
public function rewind() {
$this->index = 0;
}
/**
* 現在位置が有効かどうかを調べる
* @return 成功した場合に TRUE を、失敗した場合に FALSE を返します。
*/
public function valid() {
return ($this->current() < $this->to);
}
}
$iterator = new RangeIterator(10, 20);
foreach ($iterator as $key => $value) {
echo "{$key} => {$value}\n";
}
実行結果
0 => 10
1 => 11
2 => 12
3 => 13
4 => 14
5 => 15
6 => 16
7 => 17
8 => 18
9 => 19
Pingback: PHPのIteratorAggregateインターフェースを継承してforeach文でループできるクラスを作成する « 山本隆の開発日誌