php產生器對象

來源:互聯網
上載者:User
當一個產生器函數被第一次調用,會返回一個內部Generator類的對象. 這個對象以和前台迭代器對象幾乎同樣的方式實現了Iterator 介面。

Generator 類中的大部分方法和Iterator 介面中的方法有著同樣的語義, 但是產生器對象還有一個額外的方法: send().

CautionGenerator 對象不能通過new執行個體化

Example #1 The Generator class

<?php    class Generator implements Iterator {        public function rewind(); //Rewinds the iterator. 如果迭代已經開始,會拋出一個異常。        public function valid(); // 如果迭代關閉返回false,否則返回true.        public function current(); // Returns the yielded value.        public function key(); // Returns the yielded key.        public function next(); // Resumes execution of the generator.        public function send($value); // 發送給定值到產生器,作為yield運算式的結果並繼續執行產生器.    }?>

Generator::send()

當進行迭代的時候Generator::send() 允許值注入到產生器方法中. 注入的值會從yield語句中返回,然後在任何使用產生器方法的變數中使用.

Example #2 Using Generator::send() to inject values

<?php    function printer() {        while (true) {            $string = yield;            echo $string;        }    }    $printer = printer();    $printer->send('Hello world!');?>

以上常式會輸出:

Hello world!
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.