XCS
XCS

Reputation: 28147

PHP' if' spanning in different code blocks

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

Upvotes: 1

Views: 102

Answers (5)

ghbarratt
ghbarratt

Reputation: 11711

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.

Upvotes: 1

Nicol&#225;s Ozimica
Nicol&#225;s Ozimica

Reputation: 9738

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.

Upvotes: 0

Naftali
Naftali

Reputation: 146310

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 }

Upvotes: 1

Cal
Cal

Reputation: 7157

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.

Upvotes: 0

Brad
Brad

Reputation: 163272

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.

Upvotes: 0

Related Questions