生成器
PHP Manual

Generator objects

When a generator function is called for the first time, an object of the internal Generator class is returned. This object implements the Iterator interface in much the same way as a forward-only iterator object would.

Most methods in the Generator class have the same semantics as the methods in the Iterator interface, but generator objects also have one additional method: send().

Caution

Generator objects cannot be instantiated via new.

Example #1 The Generator class

<?php
class Generator implements Iterator {
    public function 
rewind();          // Rewinds the iterator. If
                                       // iteration has already begun,
                                       // this will throw an exception.

    
public function valid();           // Returns false if the
                                       // iterator has been closed.
                                       // Otherwise returns 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);      // Sends the given value to the
                                       // generator as the result of
                                       // the yield expression and
                                       // resumes execution of the
                                       // generator.
}
?>

Generator::send()

Generator::send() allows values to be injected into generator functions while iterating over them. The injected value will be returned from the yield statement and can then be used like any other variable within the generator function.

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 Manual