Why would one omit the close tag?

2018-12-31 01:08发布

I keep reading it is poor practice to use the PHP close tag ?> at the end of the file. The header problem seems irrelevant in the following context (and this is the only good argument so far):

Modern versions of PHP set the output_buffering flag in php.ini If output buffering is enabled, you can set HTTP headers and cookies after outputting HTML because the returned code is not sent to the browser immediately.

Every good practice book and wiki starts with this 'rule' but nobody offers good reasons. Is there another good reason to skip the ending PHP tag?

14条回答
君临天下
2楼-- · 2018-12-31 02:10

Pros

Cons

  • Avoids headache with adding inadvertently whitespaces after the closing tag, because it breaks the header() function behavior... Some editors or FTP clients / servers are also known to change automatically the end of files (at least, it's their default configuration)
  • PHP manual says closing tag is optional, and Zend even forbids it.

Conclusion

I would say that the arguments in favor of omitting the tag look stronger (helps to avoid big headache with header() + it's PHP/Zend "recommendation"). I admit that this isn't the most "beautiful" solution I've ever seen in terms of syntax consistency, but what could be better ?

查看更多
还给你的自由
3楼-- · 2018-12-31 02:10

There are 2 possible use of php code:

  1. PHP code such as class definition or function definition
  2. Use PHP as a template language (i.e. in views)

in case 1. the closing tag is totally unusefull, also I would like to see just 1 (one) php open tag and NO (zero) closing tag in such a case. This is a good practice as it make code clean and separate logic from presentation. For presentation case (2.) some found it is natural to close all tags (even the PHP-processed ones), that leads to confution, as the PHP has in fact 2 separate use case, that should not be mixed: logic/calculus and presentation

查看更多
登录 后发表回答