# Generators

> Section in “New and Extended Functionality › Reflection API” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/reflection-api/generators/>

The `ReflectionGenerator` class has been added for introspecting `Generator` objects:

``` php
function xrange(int $start, int $end, int $step = 1) {
    for ($i = $start; $i <= $end; $i += $step) {
        yield $i;
    }
}

$generator = new ReflectionGenerator(xrange(1, 2, 1));

var_dump($generator->getExecutingGenerator());
var_dump($generator->getExecutingFile());
var_dump($generator->getExecutingLine());
var_dump($generator->getTrace());
var_dump($generator->getFunction());
var_dump($generator->getThis());
```

Executing the code shown above will print the output shown below:

    array(0) {
    }
    int(3)
    string(17) "example.php"
    object(Generator)#2 (0) {
    }
    object(ReflectionFunction)#3 (1) {
      ["name"]=>
      string(6) "xrange"
    }
    NULL

The `getExecutingGenerator()` method returns the executing `Generator` object, `getExecutingFile()` and `getExecutingLine()` return the full path and name of the file in which as well as the number of the line on which the executing generator was created, `getFunction()` returns an `ReflectionFunctionAbstract` instance that represents the generator function, `getTrace()` returns the trace of the currently executing generator, and `getThis()` returns the `$this` reference the generator has access to if it was declared in a class.

---

Previous: [Scalar Type Declarations](https://php7explained.com/new-and-extended-functionality/reflection-api/scalar-type-declarations/index.html.md) | Next: [References](https://php7explained.com/new-and-extended-functionality/reflection-api/references/index.html.md)
