1

I was trying to get yield working and I copied and pasted the following code from http://php.net/manual/en/language.generators.syntax.php into an empty file and got the error Parse error: syntax error, unexpected '$i' (T_VARIABLE) in [FILENAME]

I'm running XAMPP v3.2.1 which has been working perfectly for the rest of my code (haven't used a yield statement yet) and PHP 5.4.16.

Any idea what I'm doing wrong or what I should do?

<?php
function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}

$generator = gen_one_to_three();
foreach ($generator as $value) {
    echo "$value\n";
}
?>

the code has no error if you replace yield with echo

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Derwent
  • 606
  • 1
  • 5
  • 13

2 Answers2

8

yield is available only on PHP versions > 5.5.

If you try to use it on previous versions, you'll get a T_VARIABLE parse error.

See 3v4l demo.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • ahhhh, right! Thanks. That's a cool little demo. Do you have any recommendations for how to implement generators in 5.4? – Derwent Oct 12 '13 at 08:35
  • 1
    @Derwentx: Nope, sorry. How about ugprading to `5.5`? – Amal Murali Oct 12 '13 at 10:24
  • You can run a token parser, find the yield tokens and replace them with a call count dependent switch-case structure, or split them up into multiple closures... It can be done with a lot of work, but I don't think it worth the effort. You should use something else, for example promises, if you want similar functionality. I [currently write a lib](https://github.com/inf3rno/php-tasks) for php control flow which uses similar interface as generators does. – inf3rno Apr 15 '14 at 01:09
-2

you must surround the yield statement with parentheses

function gen_one_to_three() {

    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
             yield ($i);    
    }

}

$generator = gen_one_to_three();
foreach ($generator as $value) {
    echo "$value\n";
}