1

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

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so if the parser ignores that, how is the X not being shown if the condition is false? O_o
Because the interpreter will handle it rather than the parser. The interpreter will determine the outcome of the conditional before making a decision of what to skip over. PHP will skip the blocks where the condition is not met, even though they are outside of the PHP open/close tags. PHP skips them according to the condition since the PHP interpreter will jump over blocks contained within a condition that is not met. (I am almost quoting this from the manual.)
1

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 }

Comments

0

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.

Comments

0

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.

1 Comment

Answers have to be a certain length because a "Yes" with no explanation isn't very helpful..
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.