I want to use some methods which use Generator
s as their return type and by-reference. However, the problem is that a method gets another method's return value, that is returned by-reference and is a Generator
, and returns it by-reference. Plus, nearly all methods return a value after yielding one or more values.
Let's see in a code:
class YieldFromByReferenceTest
{
public $data = [
"Ubuntu",
"CentOS",
"Fedora"
];
protected function &sampleGenerator(): \Generator
{
foreach ($this->data as $key => &$datum) {
yield $key => $datum;
}
// This is just a sample return type
return true;
}
public function &useGenerator(): \Generator
{
$generator = $this->sampleGenerator();
// Return $generator?
}
}
Firstly, yield from
came in my mind. However, when I try to use it, it gives me the following error:
PHP Fatal error: Cannot use "yield from" inside a by-reference generator in ./test.php on line xx
That looks strange to me. I don't know why it does not work (as in my mind, it should work). So, my questions are:
In this case, why
yield from
doesn't work as expected and an error is generated? Shouldn't it work?What are the alternative solutions?
Thank you!