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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With