实现迭代器(Iterator)接口

<?php

/**
 * 实现迭代器(Iterator)接口
 */
class MyIterator implements Iterator
{
    private $data = array();

    public function current()
    {
        return current($this->data);
    }

    public function next()
    {
        next($this->data);
    }

    public function key()
    {
        return key($this->data);
    }

    public function valid()
    {
        return key($this->data) !== null;
    }

    public function rewind()
    {
        reset($this->data);
    }

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

$myIterator = new  MyIterator();

$data = array(
    'Leon' => '黎明',
    'Jacky' => '张学友',
    'Aaron' => '郭富城',
    'Andy' => '刘德华',
);

$myIterator->setData($data);

foreach ($myIterator as $key => $value) {
    echo "{$key} => {$value}" . PHP_EOL;
}
// ========== 输出结果 ==========
// Leon => 黎明
// Jacky => 张学友
// Aaron => 郭富城
// Andy => 刘德华

Copyright © 2024 码农人生. All Rights Reserved