Here is a simple JavaScript generator (via: http://blog.carbonfive.com/2013/12/01/hanging-up-on-callbacks-generators-in-ecmascript-6/ )
function* powGenerator() { var result = Math.pow(yield "a", yield "b"); return result; } var g = powGenerator(); console.log(g.next().value);
I'm trying to simulate something like this with PHP, but this is a bit of a headache.
<?php function powGenerator() { return pow((yield 'a'), (yield 'b')); }
Before I go any further, I get this error in PHP
Fatal error: generators cannot return values using "return"
Well, maybe I'm just using a different income to get the final value? ...
<?php function powGenerator() { yield pow((yield 'a'), (yield 'b')); } $g = powGenerator();
Ok, so I got my meaning back, but there are two main problems.
Where is my "a" go? - Please note that in the JS example, I was able to access the values of "a" and "b" , as well as the final result of 100 .
The generator is not done yet! - I need to call send extra time to complete the generator
$g->valid(); //=> true $g->send('?'); //=> null $g->valid(); //=> false
From PHP Generator :: send
public mixed Generator::send ( mixed $value )
Sends the setpoint to the generator as a result of the current yield expression and resumes the generator.
If the generator does not have a yield expression when calling this method, first, before sending the value, first go to the first yield expression. Essentially, there is no need to “run” PHP generators with a call to Generator :: next () (as is done in Python).
Emphasis on "As such, there is no need to" calculate "PHP generators using Generator::next() ." OK, but what does that mean? I don’t need to “refuel” it, as an example of JavaScript, but the first received value is also swallowed.
Can someone explain how you are going to run generators without using foreach ?