note 130249 added to generator.current
| From: | booleantype1990@gmail.com | Date: | Tue, 15 Apr 2025 16:11:09 +0000 |
| Subject: | note 130249 added to generator.current | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-222088@lists.php.net to get a copy of this message | ||
I do not agree with ctx2002 at gmail dot com, because they misinterpreted the gib-o-master's
post. gib-o-master wrote: "current() advances *untouched* generator", "the *first*
step/iteration", and this is the key. "the following calls will not" - this is
another key.
ctx2002 at gmail dot com "touches" the generator by calling
valid:
<?php
function y1()
{
yield 1;
}
$g = y1();
// Here is the first "touch". So generator isn't untouched anymore.
// At this point generator has been already reached the first yield,
// so if we call current after that, we'll get "1".
if ($g->valid()) {
echo "valid\n";
}
// Here generator is already *touched*, so next calls
// of valid, current DO NOT advance the generator.
// next will do.
echo "current v:" . $g->current() . "\n"; //at this point, PHP outputs
current v:1
// ...
?>
Please, look at the following example:
<?php
function y1()
{
echo "I've been advanced by current(), but only in the first iteration";
yield 1;
yield 2;
}
$g = y1(); // No output.
// "I've been advanced by current(), but only in the first iteration".
// int(1)
var_dump($g->current());
// No advance anymore, so still int(1).
var_dump($g->current());
?>
This is standard behavior and is described in RFC: "If the generator is not yet at a yield
statement (i.e. was just created and not yet used as an iterator), then any call to rewind, valid,
current, key, next or send will resume the generator until the next yield statement is hit."
BTW, send WILL advance the generator. But it's an another story: about consuming,
not iterating.
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 88.156.209.7)
----
Manual Page -- https://php.net/manual/en/generator.current.php
Edit -- https://main.php.net/note/edit/130249
Del: integrated -- https://main.php.net/note/delete/130249/integrated
Del: useless -- https://main.php.net/note/delete/130249/useless
Del: bad code -- https://main.php.net/note/delete/130249/bad+code
Del: spam -- https://main.php.net/note/delete/130249/spam
Del: non-english -- https://main.php.net/note/delete/130249/non-english
Del: in docs -- https://main.php.net/note/delete/130249/in+docs
Del: other reasons-- https://main.php.net/note/delete/130249
Reject -- https://main.php.net/note/reject/130249
Search -- https://main.php.net/manage/user-notes.php