问题
Possible Duplicate:
why in some scripts they omit the closing php tag ?>
As explained in the Code Igniter style guide, it seems that PHP closing tags are optional. It even say you should avoid it for several reasons.
Anyone would have some more information about this issue ?
Thanks !
回答1:
One reason people avoid the closing ?> tag is avoid "the headers already sent error" due to line breaks or other invisible characters after the ?> tag.
回答2:
There's really not too much to say about the issue.
A PHP file ending like so:
<php
//code
?>
will actually make PHP send headers to the client, because of the whitespace after the closing ?>
tag, which you can see if you highlight the code block. Whitespace or linebreaks at the end of files can be easy to miss and hard to track down.
Once the headers are sent, it's impossible to do stuff like change the status line or the content type.
Since a closing tag is implied at the end of a file, you can just omit the closing tag for files with only PHP code. If you do, any trailing whitespace will be treated as whitespace in code, not whitespace in content, and will be ignored.
回答3:
It's perfectly valid to omit closing tag. One of the reasons to do so is to avoid unwanted whitespace which might conflict with headers.
回答4:
It used to avoid sending headers at included files. For example if your included file contains PHP closing tag and space charachter on it or newline this file sends headers and you can't change headers information in future.
回答5:
From the manual ( http://www.php.net/manual/en/language.basic-syntax.instruction-separation.php ):
Note: The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
回答6:
I usually use the closing tags, but have heard about this code style when using Code Igniter. My guess is that by leaving out the closing tag, you avoid possible issues with "whitespace" characters that could end up breaking your sessions, which can cause a "headers already sent" error.
来源:https://stackoverflow.com/questions/3344506/php-closing-tag-unnecessary