According to the php manual.
Simplifying: One is a return and one value, another is to create a Generator.
YIELD
A yield statement looks very much like a return, except that instead of stopping the execution of the function and returning, yield yields a value for the loop code over the generator and pauses the execution of the generator function.
I'm not going to talk about Generators here, because this question explains it very well:
What are the advantages to use a Generator (yield) in PHP?
So when you use yield
you are indicating that the value passed to it will be part of a desired iteration step. There will be a "pause" in the iteration and those values will be returned in an object of class Generator
.
Generator in turn implements an interface called Iterator
in PHP. It would be good to understand its usage, because in this case, it would not be important to learn only the Generator syntax before learning what iterator is.
If you know what a Iterator
is, then we can say: When you call a Generator
object with foreach
, you are invoking the methods in the following sequence:
foreach (gen() as $key => $value) {
}
Equivalent to:
$gen = gen();
$gen->rewind();
while ($gen->valid()) {
$key = $gen->key();
$value = $gen->current();
$gen->next();
}
RETURN
The return
, which translates as "return", serves to return a value for a function. There are two different cases, since in the first case, Generator
is just a "pause" for the loop that was proposed therein. Already return
represents the definite value returned for that function call.
Can I use the two together?
Depends on the version of PHP you are using. If you are using versions prior to PHP 7, you will get an exception when trying to set return
and yield
to the same function.
In PHP 7, you can do this. In this case, you will have to use the Generator::getReturn
method.
function gen()
{
yield 1 => 2;
yield 3 => 4;
return 5;
}
gen()->getReturn(); // 5
Other differences
The return
can be used outside a function, since yield
can not.
The best way to get a generator
through yield
, having the Generator object directly in a variable, is only with the self invoking function. But it's only available for PHP 7.
Example:
$gen = (function ()
{
yield "A" => "B";
})();
var_dump($gen); // Generator(object);
The yield
can be processed according to the number of declarations, return
not. You can only have more than one return
in the function, but when the first one is executed, the rest will be ignored. yield
is not like this.
function hello()
{
yield "Stack Overlow";
yield "Mandioca";
yield "Milho";
}
$gen = hello();
var_dump($gen->current());
$gen->next();
var_dump($gen->current());
The output will be:
string(13) "Stack Overlow"
string(8) "Mandioca"