Ok, someone has just shown me a piece of PHP code and at the end of the file I've seen a stray <?php } ?>
. I thought that should give a compilation error, but it doesn't.
Why is:
<?php
if(1==1){
?>
X
<?php } ?>
valid?
Is it safe to split a statement into multiple php blocks?
PS: I was expecting for something more from the answers then "yes" :D
From the manual:
Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content. This allows PHP to be embedded in HTML documents, for example to create templates.
Welcome to the mysterious world of PHP.
Yes that is fine, but I would suggest:
<?php if(1==1):?>
X
<?php endif; ?>
It makes it a little more readable then random {
and }
Safe? Yes.
Readable? Not really.
Avoid mixing your PHP logic with your HTML where possible. There are few times when this is a good idea, as it makes reading through and understanding your code difficult.
Yes, this is fine.
It's often useful to drop out of "php mode" for large blocks of HTML - you'll see this technique used anywhere HTML and PHP are mixed.
It is valid, but not recommended
if you want to have a code that is maintainable and readable in the long run.
You must bear in mind that every time you "exit" from PHP, you are entering HTML.