PHP 7.1.18 Released

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().


Generator objects cannot be instantiated via new.

Przykład #1 The Generator class

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() 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.

Przykład #2 Using Generator::send() to inject values

function printer() {
    while (
true) {
$string yield;

$printer printer();
$printer->send('Hello world!');

Powyższy przykład wyświetli:

Hello world!
add a note add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top