Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does output in an alternate-syntax switch statement cause a syntax error

Tags:

php

I recently encountered the switch statement syntax error described at http://php.net/manual/en/control-structures.alternative-syntax.php

My IDE (phpstorm) detected the error, but it didn't provide any useful context for correction. The code certainly did produce a fatal error when including the file as a template.

The manual page's warning:


Warning Any output (including whitespace) between a switch statement and the first case will result in a syntax error. For example, this is invalid:

<?php switch ($foo): ?>
    <?php case 1: ?>
    ...
<?php endswitch ?>

Whereas this is valid, as the trailing newline after the switch statement is considered part of the closing ?> and hence nothing is output between the switch and case:

<?php switch ($foo): ?>
<?php case 1: ?>
    ...
<?php endswitch ?>

The manual page offers no explanation. Some user comments on the page don't explain anything either; they simply restate that whitespace isn't allowed.

Why is this a syntax error?

like image 984
Seth Battin Avatar asked Jan 27 '16 21:01

Seth Battin


1 Answers

It just is.

It's a syntax error for the same reason that this is:

<?php

$foo = 1;
switch ($foo) {
?>
    This can't be here.
    <?php
    case 1:
        echo "I'm one";
        break;
    case 2:
        echo "I'm two";
        break;
}

This results in:

[27-Jan-2016 22:21:08 Europe/Berlin] PHP Parse error: syntax error, unexpected ' This can't be here.', expecting case (T_CASE) or default (T_DEFAULT) or '}' in /path/file on line 7

The only thing that can follow a switch is a case. It's just how the language works.

The whitespace-specific limitation with the alternative syntax is one of the reasons that it is the alternative syntax: it results in ugly formatting and lacks indentation where one would normally expect to see it.

like image 83
elixenide Avatar answered Nov 09 '22 21:11

elixenide