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表达式的结果并继续执行生成器. } ?>
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('Hello world!'); ?>
The above routine will output:
Hello world!