PHP Pro Tip: Don't close your PHP documents with ?>

Recently on my Twitter I mentioned this exact tip, "PHP Pro Tip: Don't close your PHP documents with ?>.", and got many responses asking why or if it's possible. I will briefly explain the benefits of this technique and when it applies. Many assumed I meant that you should never close your PHP scopes with ?>, but that's not the case, I was merely stating that the closing tag (at the very very bottom of your PHP file) does not need to be there.

If you are within a template file that has multiple opening and closing PHP tags, then of course it would be required to close those. If you have a PHP class or file that's purely PHP and consists of no front-end markup, then the closing tag at the bottom of the page is optional. It even says so in the official PHP.net documentation.

The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted white space will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted white space at the end of the parts generated by the included files.

Now onto the benefits to this technique. The main benefit is that it solves the "unwanted white space" at the beginning of the next document, causing it to error out and spew HTTP headers. It does so by keeping the PHP scope open at the end of the script, and allowing included files to continue within the scope and not fail. It also means you don't have to spend the time making sure there is no white space or new lines at the end of your files.

Very handy if you ask me. So just a heads up with a little tip. Enjoy :]

2 Comments

  • At first it took some getting used to. But if you can choose: why not. It has more advantages than disadvantages.

    After a while closing tags just seemed old-fashioned to me.
    This evolved and now they hurt the face; and whenever we meet: one of us has got to go
  • i actually like the closing tags^^
    and as long as you dont use garbige IDEs (like windows wordpad) everything's fine
    mine for example automatically strips all trailing white spaces from every line (especially in the last row after the ?>)

    but i agree that it could be helpful for class library files etc