ScotlandPHP

Generator::getReturn

(PHP 7)

Generator::getReturnGet the return value of a generator

Description

public mixed Generator::getReturn ( void )

Parameters

This function has no parameters.

Return Values

Returns the generator's return value once it has finished executing.

Examples

Example #1 Generator::getReturn() example

<?php

$gen 
= (function() {
    
yield 1;
    
yield 2;

    return 
3;
})();

foreach (
$gen as $val) {
    echo 
$valPHP_EOL;
}

echo 
$gen->getReturn(), PHP_EOL;

The above example will output:

1
2
3

add a note add a note

User Contributed Notes 3 notes

up
0
brandon at cryy dot com
17 days ago
I'm not quite sure -- I feel there is an ambiguity issue here with returning a value inside a generator and ->getReturn() method of such generator as I have been able to return an array of sorts, something like this:

function dequeue(){
try{
  foreach($this->buffer->data as $data){ ... }
}
  return $statistics;
}

foreach(($generator = $this->dequeue()) as $bdata){
.....
}

if($statistics = $generator->getReturn()){
// generator returns $statistics
}

Obviously this is not a complete example, but $statistics does become available with the returned array.
up
-1
pemapmodder1970 at gmail dot com
2 months ago
The note by jm at guide42 dot com is inaccurate. Generator::getReturn() does not check the existence of the return statement, but rather whether the function has returned (finished executing).

<?php
function f(){
  yield;
}

f()->getReturn(); // Exception: Cannot get return value of a generator that hasn't returned

$f = f();
$f->next(); // NULL
$f->getReturn(); // NULL, because having no return statement implies an empty `return;`, and the void return value is resolved to null.
up
-4
jm at guide42 dot com
1 year ago
Be careful that `->getReturn()` will throw an exception if no return is present in the generator:

<?php
function g() {
    yield
'A';
}
try {
   
g()->getReturn();
} catch (
Exception $ex) {
   
var_dump($ex->getMessage());
   
// Cannot get return value of a generator that hasn't returned
}
?>
To Top