Home > Backend Development > PHP Tutorial > php generator object

php generator object

伊谢尔伦
Release: 2016-11-23 09:06:44
Original
1626 people have browsed it

When a generator function is called for the first time, it will return an object of the internal Generator class. This object implements the Iterator interface in almost the same way as the front iterator object.

Most of the methods in the Generator class have the same semantics as the methods in the Iterator interface, but the generator object has an additional method: send().

CautionGenerator objects cannot be instantiated through 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表达式的结果并继续执行生成器.
    }
?>
Copy after login

Generator::send()

Generator::send() allows values ​​to be injected into generator methods when iterating. The injected value will be returned from the yield statement and then used in any generator method Used in variables.

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

<?php
    function printer() {
        while (true) {
            $string = yield;
            echo $string;
        }
    }
    $printer = printer();
    $printer->send(&#39;Hello world!&#39;);
?>
Copy after login

The above routine will output:

Hello world!
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template