Some people swear by closing their PHP files with ?>
, some say it's more optimized to leave it off.
I know that it's not essential to have it on there, I'm just wondering what the pros and cons are of doing this, and what best practice is.
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityIt's not so much a matter of performance - parsing the trailing ?>
is trivial and won't make any noticable difference at all, unless you're including a million files per second.
IIRC, php.net recommends NOT adding the ?>
, and the reasons go something like this:
?>
, which will be output to the client, which in turn can lead to obscure 'headers already sent' errors (this happens when an included file contains whitespace, and you try to set a header after including that file)No, they are wrong.
?>
is optional in PHP at the end of a file. And you'll find good reason for this. The most important one is that an empty space at the end of a file will not prevent you from sending headers. This is a difficult bug to spot because you can find it in any file anywhere.
The usual way to do is putting a closing tag when PHP is mixed with HTML and not putting it for pure PHP files. It's even a coding standard from ZEND framework and many others.
Optimized means that the code run faster. This is easy to prove them wrong. Profile the code and figure out that they are telling you bullshit.
I think it is recommended to newbies to avoid adding it so that they don't cause extra newline chars to be sent accidentally. Since it is not essential to have it like you have mentioned, I think the general reasoning is that better leave it off to avoid mistakes.
I don't think there is any "optimization" involved with it.
I would point you to here: https://stackoverflow.com/questions/4410704/php-closing-tag and here : https://stackoverflow.com/questions/3219383/why-do-some-scripts-omit-the-closing-php-tag
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.