php 5 Iterator 內部介面

來源:互聯網
上載者:User

    class MyIterator implements Iterator
    {
        private $var = array();
        public function __construct($array){
            if(is_array($array)){
                $this->var = $array;
            }
        }

        public function rewind(){
            echo "rewinding/n";
            reset($this->var);      #reset() 將 array 的內部指標倒回到第一個單元並返回第一個數組單元的值。
        }

        public function current(){
            $var = current($this->var);
/*
每個數組中都有一個內部的指標指向它“當前的”單元,初始指向插入到數組中的第一個單元。
current()函數返回當前被內部指標指向的數組單元的值,並不移動指標。
如果內部指標指向超出了單元列表的末端,curret() 返回 FALSE。
*/
            echo "current: $var/n";
            return $var;
        }

        public function key(){
            $var = key($this->var);
/*
mixed key ( array array)
key() 返回數組中當前單元的鍵名。
*/
            echo "key: $var/n";
            return $var;
        }

        public function next(){
            $var = next($this->var);
/*
mixed next ( array array)
返回數組內部指標指向的下一個單元的值,或當沒有更多單元時返回 FALSE。
next()和current()的行為類似,只有一點區別,在傳回值之前將內部指標向前移動一位。
這意味著它返回的是下一個數組單元的值並將數組指標向前移動了一位。
如果移動指標的結果是超出了數組單元的末端,則 next() 返回 FALSE。
*/
            echo "next: $var/n";
            return $var;
        }

        public function valid(){
            $var = $this->current() !== false;
            echo "valid: {$var}/n";
            return $var;
        }
    }

    $values = array(1, 2, 3);
    $it = new MyIterator($values);
    foreach($it as $a => $b){
        print "$a => $b/n";
    }
?>
/*    輸出結果如下
rewinding
current: 1
valid: 1
current: 1
key: 0
0 => 1
next: 2
current: 2
valid: 1
current: 2
key: 1
1 => 2
next: 3
current: 3
valid: 1
current: 3
key: 2
2 => 3
next:
current:
valid:

foreach語句遍曆Iterator介面的過程如下:
迴圈之前rewind()方法使迭代器指標指向第一個元素,隨後調用valid()方法
在valid()方法調用中current()方法先被調用。接著foreach語句自動調用,
current(),key(), next()
當valid()返回FALSE的時候迭代結束
*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.