php设计模式-迭代器

class CustomIterator implements Iterator
{
    private $_data;
    private $_index = 0;

    public function __construct($data)
    {
        $this->_data = $data;
    }

    /**
     * 返回当前指针指向的元素
     * @return mixed
     */
    public function current()
    {
        return $this->_data[$this->_index];
    }

    /**
     * 指针向前推一位
     */
    public function next()
    {
        $this->_index ++;
    }

    /**
     * 重置指针,将指针指向第一个元素
     */
    public function rewind()
    {
        $this->_index = 0;
    }

    /**
     * 返回当前指针位置
     * @return int|mixed
     */
    public function key()
    {
        return $this->_index;
    }

    /**
     * 检测指针当前指向是否有效
     * @return bool
     */
    public function valid()
    {
        return count($this->_data) > $this->_index;
    }
}

$data = array(
    ['name' => 'zhangsan', 'age' => 12, 'career' => 'engineer'],
    ['name' => 'lisi', 'age' => 12, 'career' => 'engineer'],
    ['name' => 'waner', 'age' => 12, 'career' => 'engineer'],
    ['name' => 'faguan', 'age' => 12, 'career' => 'engineer'],
);

$obj = new CustomIterator($data);

echo '<pre>';
foreach ($obj as $key => $user) {
    print_r($user);
}

echo '---------------------------------------------------<br>';
// 重置指针,相当于数组里的reset()方法
$obj->rewind();

while ($obj->valid())
{
    print_r($obj->current());
    $obj->next();
}

  结果:

Array
(
    [name] => zhangsan
    [age] => 12
    [career] => engineer
)
Array
(
    [name] => lisi
    [age] => 12
    [career] => engineer
)
Array
(
    [name] => waner
    [age] => 12
    [career] => engineer
)
Array
(
    [name] => faguan
    [age] => 12
    [career] => engineer
)
---------------------------------------------------
Array
(
    [name] => zhangsan
    [age] => 12
    [career] => engineer
)
Array
(
    [name] => lisi
    [age] => 12
    [career] => engineer
)
Array
(
    [name] => waner
    [age] => 12
    [career] => engineer
)
Array
(
    [name] => faguan
    [age] => 12
    [career] => engineer
)

  

posted @ 2020-07-21 09:48  coder_xds  阅读(109)  评论(0编辑  收藏  举报