Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of not including a closing `?>` tag in a PHP class file? [duplicate]

Tags:

php

Possible Duplicate:
PHP closing tag

I have seen many PHP classes files which do not have a closing ?> so instead of this:

<?php
class DataTypeLine extends DataType {
    ...
}
?>

they just have this:

<?php
class DataTypeLine extends DataType {
    ...
}

I also notice when I create a new PHP file in Eclipse Helios, it defaults to having only a starting <?php tag but no ending tag ?>.

What is the advantage of not having an ending ?> tag?

like image 314
Edward Tanguay Avatar asked Dec 13 '10 22:12

Edward Tanguay


People also ask

Is it OK to not close the PHP tag?

If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file.

Why is it considered a best practice to avoid using a PHP closing tag ?> In PHP files that contain only PHP code?

It is recommended that a closing PHP tag shall be omitted in a file containing only PHP code so that occurrences of accidental whitespace or new lines being added after the PHP closing tag, which may start output buffering causing uncalled for effects can be avoided.

Which of the following is not valid PHP code closing tag?

Only <! !> is not valid.

Which of the following is the open and closing tags of PHP?

php and ?>. These are called PHP's opening and closing tags. Statements witihn these two are interpreted by the parser. PHP script within these tags can be embedded in HTML document, so that embedded code is executed on server, leaving rest of the document to be processed by client browser's HTML parser.


2 Answers

No real advantage—it helps ensure there's no inadvertent whitespace that's outputted by adding new lines at the end of the file which can mess up things like sending headers and such.

For example, a file like this:

<?php
    /* do stuff */
?>

<!-- note the empty space above, this comment not really part of the code -->

will break a file that uses it like this

<?php
    require 'myfile.php';
    header('Location: http://example.com/');
?>

with output already sent errors, because of those blank lines in the first file. By not using the ?>, you avoid that potential problem.

like image 184
Aaron Yodaiken Avatar answered Sep 23 '22 17:09

Aaron Yodaiken


From the PHP documentation

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.

like image 39
bimbom22 Avatar answered Sep 25 '22 17:09

bimbom22