The Optional Closing Tag
You know that a block of PHP code begins with <?php and ends with ?> and anything outside of that will be sent as output. What you may or may not know is that the closing tag is optional at the end of a file.
So should you include this closing tag in your PHP files? That question was put out to the PHP community and here are the latest results:
Arguments For NO
Sure, the language is full of conveniences but what good is that bit of information? Leaving off the final closing PHP tag could have saved many hours of confusion for a number of people.
Have you ever came upon a “headers already sent” message and had no idea why? This comes up constantly in forums and lists and the solution is almost always to remove any whitespace before <?php or after ?>. This whitespace issue is the number one (possibly only) reason to argue the possition of leaving off the final closing tag.
Unintended whitespace sent as output can lead not only to issues with sending headers, but also could introduce errors in other types of output such as XML or images.
Here’s an example of how this whitespace can be introduced into a file. Line numbers are included in these examples.
--index.php-- 1 <?php 2 include 'inc.php'; 3 header("Location: http://phpnightly.com"); 4 exit; 5 ?> --inc.php-- 1 <?php 2 // some code here, maybe a hit counter 3 // this file isn't meant to output anything 4 ?> 5 6
Running index.php will produce something like
Warning: Cannot modify header information - headers already sent by (output started at \public_html\inc.php:6) in \public_html\index.php on line 3
The closing tag can have a single new line after it without causing any problems. But a new line, space, tab, anything after that will be sent as output and can cause that warning message.
Arguments For YES
Why then, given this information that it could ruin a script, would you want to use it?
- It’s a clean and definite finish to the script
- Leaving it off is just lazy. You should be sure there isn’t whitespace there
- Every tag, brace, parenthesis, etc. needs a partner
The manual states that it is optional. The Zend Framework coding standard (and others) says that it must be left off.
If you really aren’t concerned about the whitespace issue, it pretty much comes down to personal preference. Or whatever the boss says, of course.
Personally, I’ve come to prefer leaving it out. Potential issues are avoided and I don’t see a benefit to having it in there if there’s no output at the end.
