Programming - - By Craig Buckler

Should You Close PHP Tags? The Debate Continues…

I was amazed at the response to my recent article, Should You Close Your PHP Code Tags? I didn’t think it would be controversial or cause so much debate among developers!

To recap, closing PHP tags (?>) are entirely optional if you’re coding a PHP-only file and there’s no intermingled HTML. Files containing single class definitions are good candidates.

Omitting the closing tag has another benefit: it becomes impossible to accidentally add white space to the end of the file. Therefore, output cannot be sent to the browser before HTTP page headers are modified.

Many respondents considered this to be a hack and stated that PHP programmers should simply fix their code. For others, omitting the closing tag prevented the possibility of errors — even if none ever existed. This can be especially useful for projects with many contributors using different IDEs.

Respondents mostly fell into one of three groups:

  1. PHP developers, perhaps working on larger projects or teams, where omitting the closing ?> was useful, recommended, or a documented coding-standard.
  2. Coding purists, possibly with a background in XHTML or XML, who considered missing tags to be wrong.
  3. Developers from other disciplines who considered the discussion to be ridiculous!

According to the SitePoint poll, a third of PHP developers did not use a closing tag, a third considered that bad practice, and third didn’t realize it could be omitted.

For the record, I often omit the closing tag. It makes no difference to the PHP interpreter or the browser so there’s little reason to include it. However, I can appreciate why some developers dislike the coding style.

Some interesting notions were raised. The first is that the interpreter could assume PHP code by default and allow escaping into HTML, e.g.

// PHP file
<p>output HTML</p>

I suspect this idea is too revolutionary. It could possibly be added as a php.ini option, but it’d break existing applications and cause chaos.

However, pure PHP files was an idea with more potential. In essence, you’d specify that a file contained PHP code only. This could be achieved by:

  • using a special file extension, e.g. filename.pphp, or
  • using a modified include/require function, such as

include('filename.php', PHP_ONLY);

If this were implemented, your PHP code wouldn’t require opening or closing tags. In addition, the functionality could be added without affecting existing PHP applications — it would be backward compatible.

But, hey, it’s just an idea and may never go any further than this article. The PHP coding style debate will rage on…