必须实现5个方法,rewind, key, current, next, valid
class TestIterator implements Iterator {
private $start, $end;
private $cur;
public $callback;
public function __construct($start, $end, $callback) {
$this->start = $start;
$this->end = $end;
$this->callback = $callback;
}
/**
* 重新把迭代器指向列表的开始处
*
* @param
*
* @return
*/
public function rewind() {
$this->cur = $this->start;
}
/**
* 返回当前位置的关键字
*
* @param
*
* @return
*/
public function key() {
return $this->cur;
}
/**
* 返回当前位置的关键字
*
* @param
*
* @return
*/
public function current() {
return call_user_func_array($this->callback, array($this->cur));
}
/**
* 把迭代器移动到下一个关键字
*
* @param
*
* @return
*/
public function next() {
$this->cur++;
// $this->cur = $this->cur + 2;
}
/**
* 返回true/false,判断是否还有更多的值(在调用current()和key()之前使用)
*
* @param
*
* @return
*/
public function valid() {
return $this->cur <= $this->end;
}
}
$test = new TestIterator(3, 7, function($key) {
return $key * 3 + 1;
});
foreach($test as $val) {
echo $val . "</br>";
}