SwiftlyTilting: usability, reusability

Thursday, October 14, 2010

Don’t close your PHP tags!

I saw this post over at sitepoint about whether or not you should close your PHP tags. Apparently there is some debate, though to me it seems pretty clear the choice is to leave them out.

If you’re unaware, the closing ?> tag in PHP files is completely optional. It is only really required if you are mixing HTML and PHP code, which itself is not a particularly good practice. Leaving off the closing tag prevents any erroneous white space or random characters from being sent to the output. It reduces the amount of code and prevents a possible error from occurring.

I can’t really think of a good reason to leave them on (assuming your document is pure PHP). Perhaps if you are from an XML background you will feel compelled to close the tag, but it’s entirely unnecessary in PHP.

Multiple frameworks and libraries such as Zend, CodeIgniter, Drupal and others suggest you to leave off the closing PHP tag as part of their style guide or best practices documentation, and I suggest the same. This is especially important for WinBinder developers (or anyone who uses php-win.exe), where any output sent to the console immediately ends the script.

Some have suggested dropping the need for <?php from php files completely. It’s not a bad suggestion, though i sort of think of it as analogous to #!/bin/sh in unix scripts. Those tags don’t need closing tags either.

So go out there and remove all those nasty ?> tags from your code ;)


1 Comment

The argument for using the PHP closing tag is pretty much the reason you’re arguing against it:

“Leaving off the closing tag prevents any erroneous white space or random characters from being sent to the output. It … prevents a possible error from occurring.”

In other words, it hides problems in your code (i.e. erroneous white space). It’s better to have your code spit out any error it possibly could, and then make sure it doesn’t, rather than hiding the problem. The reason to use closing tags is the same reason to not using the @ error suppression symbol.

Comment by Nick Coons — Saturday, June 21, 2014 @ 5:45 pm

Validate XHTML | Word Press