官术网_书友最值得收藏!

Generator return expression

As we have seen earlier, on calling a generator function, it returns a value that is being returned by the yield expression. Before PHP7, it didn't have the return keyword returning a value. But since PHP7.0, it is possible to use the return expression as well. Here, I have used an example from the PHP documentation, as it explains it very well:

<?php

$gen = (function() {
yield "First Yield";
yield "Second Yield";

return "return Value";
})();

foreach ($gen as $val) {
echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

It will give the output as:

First Yield
Second Yield
return Value

So it clearly shows that calling a generator function in foreach will not return the return statement. Instead, it will just return at every yield. To get the return Value, this syntax: $gen->getReturn() can be used.

主站蜘蛛池模板: 屯留县| 垦利县| 清水县| 唐山市| 南投市| 中山市| 阳山县| 峨山| 田林县| 绥化市| 贡觉县| 衡山县| 西藏| 石台县| 平湖市| 青神县| 肇东市| 全州县| 博湖县| 招远市| 沾化县| 江口县| 聂拉木县| 大宁县| 星子县| 桃源县| 夏河县| 西青区| 祁阳县| 本溪| 康保县| 河北省| 镇巴县| 江都市| 文登市| 婺源县| 瓦房店市| 怀安县| 凯里市| 平湖市| 巨鹿县|