When I commit a php file to github I get the message "No newline at end of file".
It's just a warning and I remember, that for any reason it is good to have a newline at the end of a file.
But why? Is it a remnant of long gone times, does it still have advantages or is it even required in php? If yes, for what reason?
If content is added to the end of the file, then the line that was previously the last line will have been edited to include a newline character. This means that blame ing the file to find out when that line was last edited will show the text addition, not the commit before that you actually wanted to see.
So, it turns out that, according to POSIX, every text file (including Ruby and JavaScript source files) should end with a \n , or “newline” (not “a new line”) character. This acts as the eol , or the “end of line” character.
It indicates that you do not have a newline (usually '\n' , aka CR or CRLF) at the end of file. That is, simply speaking, the last byte (or bytes if you're on Windows) in the file is not a newline.
It's not required by PHP, but it can cause problems with some diff tools. The warning is a just a warning and can be ignored if desired, but I would recommend following convention and having the last character be a newline.
This is a PSR-2 convention that states:
All PHP files MUST end with a single blank line.
Why? Because utilities that are supposed to operate on files (like the diff utility) may not cope well with lines that don't end with a newline; this is how POSIX states in one of its rules:
3.206 Line
A sequence of zero or more non- <newline> characters plus a terminating character.
Therefore, lines not ending in a newline character aren't considered actual lines. Which means: if your last line is a line of code (instead of an empty line), it might be ignored by those tools and can cause your program to break!
The warning is to help you to detect a possibly defective, truncated file, on the assumption that file without a newline at the end is suspect for being truncated.
Other than that, the only reason to avoid source files without a terminating newline is to avoid the warning!
Now, in PSR-12 #2.2 Files:
All PHP files MUST use the Unix LF (linefeed) line ending only. All PHP files MUST end with a non-blank line, terminated with a single LF.
It is probably derived from the C standard: http://c0x.coding-guidelines.com/5.1.1.2.html (paragraph 123). Reasons include that some compilers or other text text processing tools process the source code line by line thus also the last source line has to end with a new-line character.
Also see this: "No newline at end of file" compiler warning - include
ing a file without new line at the end could cause similar problems like in C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With