PHP遍歷介面Iterator詳解

Thanatos發表於2019-02-16

從手冊中查到的解釋是:

Iterator extends Traversable {
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
}

當一個實現了Iterator介面的物件,被foreach遍歷時,會自動呼叫這些方法。呼叫的循序是:
rewind() -> valid() -> current() -> key() -> next()

下面來看一下簡單的程式碼:

class myIterator implements Iterator {  
    private $position = 0;  
    private $array = array(  
        "firstelement",  
        "secondelement",  
        "lastelement",  
    );    
  
    public function __construct() {  
        $this->position = 0;  
    }  
  
    function rewind() {  
        var_dump(__METHOD__);  
        $this->position = 0;  
    }  
  
    function current() {  
        var_dump(__METHOD__);  
        return $this->array[$this->position];  
    }  
  
    function key() {  
        var_dump(__METHOD__);  
        return $this->position;  
    }  
  
    function next() {  
        var_dump(__METHOD__);  
        ++$this->position;  
    }  
  
    function valid() {  
        var_dump(__METHOD__);  
        return isset($this->array[$this->position]);  
    }  
}  
  
$it = new myIterator;  
  
foreach($it as $key => $value) {  
    var_dump($key, $value);  
    echo `---------------------------`."
";
}  

以上會輸出:

/Users/thanatos/Web/study/blean.php:15:string `myIterator::rewind` (length=18)
/Users/thanatos/Web/study/blean.php:35:string `myIterator::valid` (length=17)
/Users/thanatos/Web/study/blean.php:20:string `myIterator::current` (length=19)
/Users/thanatos/Web/study/blean.php:25:string `myIterator::key` (length=15)
/Users/thanatos/Web/study/blean.php:43:int 0
/Users/thanatos/Web/study/blean.php:43:string `firstelement` (length=12)
---------------------------
/Users/thanatos/Web/study/blean.php:30:string `myIterator::next` (length=16)
/Users/thanatos/Web/study/blean.php:35:string `myIterator::valid` (length=17)
/Users/thanatos/Web/study/blean.php:20:string `myIterator::current` (length=19)
/Users/thanatos/Web/study/blean.php:25:string `myIterator::key` (length=15)
/Users/thanatos/Web/study/blean.php:43:int 1
/Users/thanatos/Web/study/blean.php:43:string `secondelement` (length=13)
---------------------------
/Users/thanatos/Web/study/blean.php:30:string `myIterator::next` (length=16)
/Users/thanatos/Web/study/blean.php:35:string `myIterator::valid` (length=17)
/Users/thanatos/Web/study/blean.php:20:string `myIterator::current` (length=19)
/Users/thanatos/Web/study/blean.php:25:string `myIterator::key` (length=15)
/Users/thanatos/Web/study/blean.php:43:int 2
/Users/thanatos/Web/study/blean.php:43:string `lastelement` (length=11)
---------------------------
/Users/thanatos/Web/study/blean.php:30:string `myIterator::next` (length=16)
/Users/thanatos/Web/study/blean.php:35:string `myIterator::valid` (length=17)

相關文章