2

I just heard of the PSR-2 coding standard in a comment on this question: Is there any reason to use the "public" keyword before method and member variable names?

I have a question on one of the rules in the PSR-2 standard:

The closing ?> tag MUST be omitted from files containing only PHP.

What is the point of that?

Community
  • 1
  • 1
developerwjk
  • 8,619
  • 2
  • 17
  • 33
  • 2
    Funny that this has 4 downvotes. It is the first result in Google when I search `psr "closing php tags"`. Thanks for posting. – Drew LeSueur Jul 29 '16 at 13:47
  • I guess that's because the other questions don't actually mention PSR-2 and this one does, so this one is better for SEO. – developerwjk Aug 02 '16 at 21:37

3 Answers3

7

It is a good universal rule not using closing tag in php scripts. Note that everything after that closing tag is sent to client (browser) even white characters so if you're using closing tag and new line or any other white character it will be sent to browser. In most cases this behavior is not desirable.

  • For example hidden white space might corrupt downloaded PDF file and it might not open in a browser. It is often difficult to seek which forgotten whitespace corrupted stream - developer's nightmare e.g. in Wordpress with 10.000++ files :-) – lubosdz Apr 03 '18 at 16:02
2

To prevent issues from trailing whitespace http://hardcorewp.com/2013/always-omit-closing-php-tags-in-wordpress-plugins/

MrGlass
  • 9,094
  • 17
  • 64
  • 89
  • That seems too simple to make such a hard and fast rule. Typically for me a file that only contains PHP code is just an include file containing functions and will not print anything unless included in another PHP file that calls those functions. – developerwjk Jun 13 '14 at 19:53
  • If there is whitespace outside of the PHP block, the whitespace will be printed during the include, which can break applications that do not expect printing at that point – MrGlass Jun 13 '14 at 19:57
1

There where you read about PSR should be explanation like this: Because you may get problems with additional (unexpected) white spaces after the closing ?> tag - they will go to the output.

agamike
  • 479
  • 3
  • 5