您的位置:首页技术文章
文章详情页

PHP基础之生成器3——生成器对象

【字号: 日期:2022-09-15 09:44:59浏览:34作者:猪猪

当一个生成器函数被第一次调用,会返回一个内部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!

标签: PHP
相关文章: