9
As of PHP 5.5, the Generator. It can be used within a function from the keyword yield
.
In the manual, we have an example where one is compared to function range(0, 1000000)
(that theoretically would spend 100MB of memory) and an implementation of xrange
through the generators (that would reduce memory consumption to 1 Kilobyte).
Example of the manual:
<?php
function xrange($start, $limit, $step = 1) {
if ($start < $limit) {
if ($step <= 0) {
throw new LogicException('Step must be +ve');
}
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('Step must be -ve');
}
for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}
}
/*
* Note that both range() and xrange() result in the same
* output below.
*/
echo 'Single digit odd numbers from range(): ';
foreach (range(1, 9, 2) as $number) {
echo "$number ";
}
echo "\n";
echo 'Single digit odd numbers from xrange(): ';
foreach (xrange(1, 9, 2) as $number) {
echo "$number ";
}
?>
In addition to the advantage of saving this memory and simplifying the use of a iterator, what are the other advantages of using the Generator in PHP?
You are the guy :)
– Wallace Maxters
@Wallacemaxters You didn’t understand the other time I told you about the rush to accept an answer http://meta.pt.stackoverflow.com/q/494/101 :)
– Maniero
I don’t remember "again". But I’m reading here :)
– Wallace Maxters
http://answall.com/questions/49561/quais-s%C3%a3o-os-benef%C3%adcios-de-usar-https/49580#comment100347_49561
– Maniero
Ah, yes. I remembered. This is true, it ends up not giving opportunity to people who are open text in the browser click on "add a reply"
– Wallace Maxters
You can, but discourage, people want to have the opportunity for your answer to be accepted, when you accept it right away when someone posts an answer, you will hardly have a second, which potentially can help you more than the first. Of course you can trade, but most do not trade, so those who answer know that it is almost certain that he will not have the acceptance and can not even answer because of this. Also because you’re already satisfied, there’s no reason to put anything else.
– Maniero
I will attend to the tips to proceed as a good community user :)
– Wallace Maxters
I read the response and the comments and I was left with a question, which accumulated something I read earlier about Yield. It is similar to "Return" or does the same thing?
– DiChrist
No, this is a typical mistake. It causes a
return
, but it is a mechanism that guards a state in order to continue where it left off. Theyield
in itself is only this, but it always works in conjunction with thereturn
, so it is common to have only one command that does both things "simultaneously". If none of the answers helped fully understand, try asking an even more specific question.– Maniero
more or less understood, I will ask a question to know the difference between Yield and Return, I think maybe can help me better :)
– DiChrist