Today the PHP team released the PHP 5.5.0 version, which includes support for generators. Reading the documentation, I noticed that it does exactly what it could do with an array.
PHP team generator example:
// Only PHP 5.5
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";
}
Result:
1
2
3
But I can do the same thing using arrays. And I can still keep compatible with earlier versions of PHP.
Take a look:
// Compatible with 4.4.9!
function gen_one_to_three() {
$results = array();
for ($i = 1; $i <= 3; $i++) {
$results[] = $i;
}
return $results;
}
$generator = gen_one_to_three();
foreach ($generator as $value) {
echo "$value\n";
}
So the question is: what is the purpose of the existence of this new feature? I got to play all examples of documentation without using the new feature, replacing it with array.
Can anyone give a good explanation and perhaps an example that is not necessarily impossible with older versions, but using generators can help in development?