PHP Closing Tags Considered Harmful

Posted in PHP and Programming on Monday, the 16th of February, 2009.

Tagged:

It may be obvious to some, but this is a mistake I still see being made a lot, and I think it's high time we got over it.

Stop using PHP closing tags. It really is that simple, and here's why.

Before I elaborate, let's illustrate what I mean. In short, this is indubitably bad:

<?php
 
echo 'Hello World!';
 
?>

Whilst this is good:

<?php
 
echo 'Hello World!';

Of course, if you're embedding HTML in PHP, or vice versa, you'll need to use closing tags to demarcate the two languages. But given a file containing only PHP code, the closing tag is completely superfluous.

Worse, the closing tag is potentially harmful, since any whitespace, accidental or otherwise, after the tag will be sent to the browser as output, with potentially catastrophic effects:

In any of these cases, tracking down an errant fragment of whitespace in a large codebase will be more pain than you really want. That's why omitting the closing tag is part of the Zend Framework coding standards among others.

So there you go. The solution is simple: stop using PHP closing tags.

Comments

Posted by Peter McDonald on Tuesday, the 24th of November, 2009.

Just recently started omitting the closing tag myself.

If you code carefully I see no reason not to include it but you are indeed correct it can stop a lot of headaches later.

Enter your comment: