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.

Posted by Neo on Saturday, the 9th of October, 2010.

So you treat the symptom rather than the root source of the problem?

sorry but treating closing tags as evil just because of the carelessness of some devs (is making sure the file ends without a whitespace / line break such a hassle?) is just a kludge imo.

and yeah, i know that this "convention" is backed up by some big names, but then again, in the end it is just a hack, you are not solving the problem, just using a loophole in the language to prevent it.

http://choosetheforce.blogspot.com/2008/05/should-you-close-that-php-tag.html

Posted by Simon Harris on Monday, the 18th of October, 2010.

Neo -

Clearly the root cause is people typing unnecessary characters for no reason.

And I assume that by "some big names", you mean "the coding standards of every single major framework and library out there".

Enter your comment: