current() advances untouched generator, same as next(), it makes the first step/iteration. the following calls will not.
non-yielded value will be NULL
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
Generator::current — Getirilen değeri döndürür
Bu işlevin bağımsız değişkeni yoktur.
Getirilen değeri döndürür.
current() advances untouched generator, same as next(), it makes the first step/iteration. the following calls will not.
non-yielded value will be NULL
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.
<?php
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}
$generator = gen_one_to_three();
foreach ($generator as $value) {
echo "regular : ".$value , PHP_EOL;
echo "With current function : ".$generator->current(),PHP_EOL;
}
?>
I think what "gib-o-master" said is wrong.
Generator::current method does not advances "untouched generator".
let me give an example:
function y1()
{
yield 1;
}
$g = y1();
if ($g->valid()) { //at this point, PHP outputs "valid"
echo "valid\n";
}
echo "current v:" . $g->current() . "\n"; //at this point, PHP outputs current v:1
if ($g->valid()) { //at this point, PHP still outputs "valid"
echo "valid\n";
} else {
echo "not valid\n";
}
if Generator::current method advances generator, then above If statement should outputs "not valid"