I just read through an example tutorial on using yield, and I have to say that I didn't understand it at all. I ran the example code, and it doesn't look like it's doing anything a regular forloop isn't able to do. It just iterate the numbers 1,2,3 like a regular forloop would do, except it's using a generator to do it? I don't understand at all, so if anyone can, please explain to me the differences between using a generator and a regular forloop.
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 "$value\n";
}
?>
Results:
1
2
3
Using just a forloop:
for ($i = 1; $i <= 3; $i++) {
echo $i;
}
Results:
1
2
3
No comments:
Post a Comment