PHP5实现foreach语言结构遍历一个类的实例

PHP5实现foreach语言结构遍历一个类

创建一个类集成Iterator接口,并实现Iterator里面的方法即可,下面见实例代码实现

<?php
class Test implements Iterator
{
    public $item = null;
    public $step = 0;
    public $key = 0;
    public function __construct(array $item=array())
    {
        $this->setItem($item);
    }

    public function setItem($item=array())
    {
        // 设置对象属性
        $this->item = $item?$item:range(1,8);
        return $this;
    }
    public function next()
    {
        $this->step = $this->step+1;
        echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
        ++$this->key;
        // 设置下次指针
    }

    public function current()
    {
        $this->step = $this->step+1;
        echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
        return $this->item[$this->key];
        // 返回当前指针的值
    }

    public function valid()
    {
        $this->step = $this->step+1;
        echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
        return isset($this->item[$this->key]);
        // 验证当前指针的值是否存在
    }
    public function rewind()
    {
        $this->step = $this->step+1;
        echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
        $this->key = 0;
        // 指针的重置
    }
    public function key()
    {
        $this->step = $this->step+1;
        echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
        return $this->key;
        // 返回当前指针
    }
}

$test = new Test();
foreach($test as $i){
    echo $i."<br/>";
}

输出结果如下:

  

原文地址:https://www.cnblogs.com/bafeiyu/p/10536898.html