Skip to content
Advertisement

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

I’m trying to make the fizzbuzz.php assignment from PHP and MySQL Web Development 5th Edition, page 193. I have typed it exactly as it is in the book, but I get a (T_CONSTANT_ENCAPSED_STRING) parse error (line 9) when I run it.

I have tried replacing yeild with echo, but then I get an improper function use error on line 27 (the foreach function).
I have tried escaping the ” with but that gives me a syntax error, unexpected string.
I have tried using ‘ instead of ” but get the enacapsed string error.

<?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 />';
}
?>

Changing yeild to echo returns a string of numbers and fizz buzz strings but they are not in the order they are supposed to be and there is still a function error at line 27.

I may have something mistyped, but I’ve checked it over and over, and this is how it’s written in the book.

Advertisement

Answer

This is too long for a comment.

I suspect that your version of PHP you are running this on, isn’t able to support it, per testing your code online on http://sandbox.onlinephpfunctions.com/.

It threw back the same error when using PHP 5.0.4.

You will need to upgrade your server if this is on a local machine. If it is hosted, you will need to contact the hosting provider to see if a newer version of PHP is available to you.

Edit:

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.

Edit #2:

(From comments)

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

Using version 5.4.45 also returned the same error, per the new test link. This feature is only available in PHP 5.5.0 and higher.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement