Why would one omit the close tag?

前端 未结 14 1606
旧巷少年郎
旧巷少年郎 2020-11-21 06:18

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

14条回答
  •  故里飘歌
    2020-11-21 07:08

    Well, there are two ways of looking at it.

    1. PHP code is nothing more than a set of XML processing instructions, and therefore any file with a .php extension is nothing more than an XML file that just so happens to be parsed for PHP code.
    2. PHP just so happens to share the XML processing instruction format for its open and close tags. Based on that, files with .php extensions MAY be valid XML files, but they don't need to be.

    If you believe the first route, then all PHP files require closing end tags. To omit them will create an invalid XML file. Then again, without having an opening declaration, you won't have a valid XML file anyway... So it's not a major issue...

    If you believe the second route, that opens the door for two types of .php files:

    • Files that contain only code (library files for example)
    • Files that contain native XML and also code (template files for example)

    Based on that, code-only files are OK to end without a closing ?> tag. But the XML-code files are not OK to end without a closing ?> since it would invalidate the XML.

    But I know what you're thinking. You're thinking what does it matter, you're never going to render a PHP file directly, so who cares if it's valid XML. Well, it does matter if you're designing a template. If it's valid XML/HTML, a normal browser will simply not display the PHP code (it's treated like a comment). So you can mock out the template without needing to run the PHP code within...

    I'm not saying this is important. It's just a view that I don't see expressed too often, so what better place to share it...

    Personally, I do not close tags in library files, but do in template files... I think it's a personal preference (and coding guideline) based more than anything hard...

提交回复
热议问题