当一个生成器函数被第一次调用,会返回一个内部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()
立即学习“PHP免费学习笔记(深入)”;
当进行迭代的时候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怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号