Sintaxis alternativa para cambiar

Hey there is an alternative syntax for switch statement in PHP, but this code doesn't work:

<div>
<?php switch($variable): ?>
<?php case 1: ?>
<div>
Newspage
</div>
<?php break;?>
<?php case 2: ?>
</div>
Forum
<div>
<?php break;?>
<?php endswitch;?>
</div>

Parse error: syntax error, unexpected T_INLINE_HTML, expecting T_ENDSWITCH or T_CASE or T_DEFAULT in /path/to/file on line #

preguntado el 25 de agosto de 12 a las 09:08

1 Respuestas

Solution for this problem is putting switch($variable): con case 1: into same block of PHP code:

<div>
<?php switch($variable): 
case 1: ?>
<div>
Newspage
</div>
<?php break;?>
<?php case 2: ?>
</div>
Forum
<div>
<?php break;?>
<?php endswitch;?>
</div>

Respondido 25 ago 12, 09:08

This is the same example from the comments in the Documentación de PHP, but is there an explainable reason for why this works, but the code in the question doesn't? Or is it just a bug in PHP? - parodia3

No importa. Esta respuesta provides some explanation. You're basically inserting a line break, which aren't allowed directly within a switch statement (outside of cases. In an if statement or a loop, it's not a problem to have a line break, but switch es diferente. - parodia3

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.