php数组中就是实现了Iterator接口,才可以使用foreach这样的语句进行遍历,
现在我们看看:
<?php
class AllUser implements \Iterator
{
protected $ids;
protected $data = array();
protected $index;
function __construct()
{
$db = Factory::getDatabase();
$result = $db->query("select id from user");
$this->ids = $result->fetch_all(MYSQLI_ASSOC);
}
//返回当前索引游标指向的元素的值
function current()
{
$id = $this->ids[$this->index]['id'];
return Factory::getUser($id);
}
//将当前索引指向下一位置
function next()
{
$this->index ++;
}
//判断当前索引游标指向的元素是否设置
function valid()
{
return $this->index < count($this->ids);
}
//将索引游标指向初始位置
function rewind()
{
$this->index = 0;
}
//返回当前索引值
function key()
{
return $this->index;
}
}