使用直接从我正在使用的书中输入的 fizzbuzz.php 时,我收到 (T_CONSTANT_ENCAPSED_STRING) 解析错误

I get a (T_CONSTANT_ENCAPSED_STRING) parse error when using fizzbuzz.php typed directly from the book I'm using

我正在尝试完成 PHP 和 MySQL Web 开发第 5 版第 193 页中的 fizzbuzz.php 作业。我已经按照书中的原样输入了它,但是当我 运行 它时,我得到一个 (T_CONSTANT_ENCAPSED_STRING) 解析错误(第 9 行)。

我曾尝试用 echo 替换 yeild,但随后在第 27 行(foreach 函数)出现函数使用不当错误。
我试过用 \ 转义 " 但这给了我一个语法错误,意外的字符串。
我尝试使用 ' 而不是 " 但得到了 enacapsed 字符串错误。

<?php
function fizzbuzz($start, $end)
{
    $current = $start;
    while ($current <= $end)
    {
        if ($current%3 == 0 && $current%5 == 0)
        {
            yield "fizzbuzz";
        }
        elseif ($current%3 == 0)
        {
            yield "fizz";
        }
        elseif ($current%5 == 0)
        {
            yield "buzz";
        }
        else
        {
            yield $current;
        }
        $current++;
    }
}

foreach(fizzbuzz(1, 20) as $number)
{
    echo $number.'<br />';
}
?>

将 yeild 更改为 echo returns 一串数字和 fizz buzz 字符串,但它们的顺序不正确,第 27 行仍然存在函数错误。

可能是我打错了,不过我反复核对过,书上是这样写的。

评论太长了。

根据 http://sandbox.onlinephpfunctions.com/.[=17= 上的在线测试,我怀疑你的 PHP 版本 运行 无法支持它]

使用 PHP 5.0.4.

时出现同样的错误

如果这是在本地机器上,您将需要升级您的服务器。如果它是托管的,您将需要联系托管服务提供商以查看是否有更新版本的 PHP 可供您使用。

编辑:

Per the manual on PHP.net under "Note":

In PHP 5, a generator could not return a value: doing so would result in a compile error. An empty return statement was valid syntax within a generator and it would terminate the generator.

编辑#2:

(来自评论)

Thank you for your help, and the links to the php sandbox, that will help me in the future. I ran phpversion() and it returned 5.4.45. It's a school server, so I'll ask them if they can upgrade it, or install PEAR on my laptop. – BackupXfer

使用版本 5.4.45 也返回相同的错误,per the new test link。此功能仅在 PHP 5.5.0 及更高版本中可用。

对于php5

function fizzbuzz($start, $end)
{
    for ($i=$start; $i<=$end; $i++)
    {
        $str = '';
        if ($i % 3 == 0)
            $str = 'Fizz';
        if ($i % 5 == 0)
            $str .= 'Buzz';

        if (empty($str))
            $str = $i;

        echo $str.'<br>';

    }
}

fizzbuzz(1, 20);