note 123290 added to generator.getreturn

From: Date: Wed, 31 Oct 2018 23:58:33 +0000
Subject: note 123290 added to generator.getreturn
Groups: php.notes 
Request: Send a blank email to php-notes+get-209572@lists.php.net to get a copy of this message
Just to be clear, the value returned by a generator is not yielded while it is running, but is available afterwards through the getReturn() method. One use for this could be to record the output of a generator so that it can be iterated over again without having to reconstruct and re-run the generator. (Indeed, one could write a generator that simply does exactly this for any given iterable.) <?php function generate_squares($n) { $record = []; for($i = 0; $i <= $n; ++$i) { yield ($record[] = $i * $i); } return $record; } $squares = generate_squares(10); foreach($squares as $s) { echo $s, ' '; } $recorded = $squares->getReturn(); echo "\nThat's [", join(', ', $recorded), "]"; ?> Recording keys as well would take a bit more work, as generators are free to repeat them but arrays aren't. ---- Server IP: 150.242.41.218 Probable Submitter: 125.237.147.42 ---- Manual Page -- http://php.net/manual/en/generator.getreturn.php Edit -- https://master.php.net/note/edit/123290 Del: integrated -- https://master.php.net/note/delete/123290/integrated Del: useless -- https://master.php.net/note/delete/123290/useless Del: bad code -- https://master.php.net/note/delete/123290/bad+code Del: spam -- https://master.php.net/note/delete/123290/spam Del: non-english -- https://master.php.net/note/delete/123290/non-english Del: in docs -- https://master.php.net/note/delete/123290/in+docs Del: other reasons-- https://master.php.net/note/delete/123290 Reject -- https://master.php.net/note/reject/123290 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#209572) next »