php生成器对象

伊谢尔伦
伊谢尔伦 原创
2016-11-23 09:06:44 1198浏览

当一个生成器函数被第一次调用,会返回一个内部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!
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。