Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generator with subgenerator
<?php
$generatorWithTwoWayCommunication = function()
{
$randomValue = mt_rand();
yield $randomValue;
$receivedFromOuterSpace = yield;
$returnValue = yield from subGenerator($receivedFromOuterSpace, $randomValue);
return $returnValue;
};
function subGenerator($valueFromOuterSpace, $randomValue)
{
yield $valueFromOuterSpace * $valueFromOuterSpace;
yield $valueFromOuterSpace * $randomValue;
return 'Lis Witalis';
};
$generator = $generatorWithTwoWayCommunication();
$valueFromFirstIteration = $generator->current();
$generator->next();
$valueFromSecondIteration = $generator->send(666);
$generator->next();
$valueFromThirdIteration = $generator->current();
$generator->next();
$valueReturnedFromGenerator = $generator->getReturn();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment