When not to close a php file?

前端 未结 3 1990
南笙
南笙 2021-01-11 21:11

I\'ve come across a tutorial (reputable one if I may add) where the closing php tag ?> was omitted. This reminded me of a previous tutorial where the author

相关标签:
3条回答
  • 2021-01-11 21:47

    Well, if you have an include file like config.php and you do not want it to output any characters because it's not meant to or you don't want to trigger "headers already sent" you can leave the closing tag off to make sure no whitespace is sent to the browser. You will find that files that are pure PHP and do not contain any content to be outputted, will generally not include a closing tag.

    The bottom line is you don't want to prematurly inject content before any headers are set. This is talked about in depth here.

    0 讨论(0)
  • 2021-01-11 21:55

    Because any whitespace after the final closing tag can cause the script to fail silently, or cause unwanted output to be sent to the browser. Some frameworks such as Zend Framework have incorporated omitting the final closing tag as a recommended practice to application developers using the ZF to help avoid such situations, and as a requirement as per their coding standards:

    For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it´ prevents the accidental injection of trailing white space into the response.

    That said, omitting closing tags is very much a workaround for a problem for which the root cause has not yet been tackled. This blog post asserts the very same.

    0 讨论(0)
  • 2021-01-11 22:05

    In addition to the other great answers, I'd like to note that this practice is mainly used in files that contain only PHP code.

    I always close the last tag while editing templates/views, so I don't have to when I add other content below that point.

    0 讨论(0)
提交回复
热议问题