PHP5實現foreach語言結構遍歷一個類的實例

PHP5實現foreach語言結構遍歷一個類php

建立一個類集成Iterator接口,並實現Iterator裏面的方法便可,下面見實例代碼實現this

<?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/>";
}

輸出結果以下:spa

相關文章
相關標籤/搜索