PHP' if' spanning in different code blocks

Go To StackoverFlow.com

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

2012-04-05 19:08
by Cristy


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.

2012-04-05 19:13
by ghbarratt
Ok, so if the parser ignores that, how is the X not being shown if the condition is false? O_ - Cristy 2012-04-05 19:14
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. - ghbarratt 2012-04-05 19:35


2

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 }

2012-04-05 19:10
by Neal


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.

2012-04-05 19:09
by Brad


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.

2012-04-05 19:09
by Cal
Answers have to be a certain length because a "Yes" with no explanation isn't very helpful. - Brendan Long 2012-04-05 19:11


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.

2012-04-05 19:10
by Nicolás
Ads