Weird PHP Yield error

China☆狼群 提交于 2019-12-13 07:13:05

问题


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


回答1:


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.




回答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";
}


来源:https://stackoverflow.com/questions/19332167/weird-php-yield-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!