5

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?

Community
  • 1
  • 1
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

3 Answers3

8

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.

Aaron Yodaiken
  • 19,163
  • 32
  • 103
  • 184
5

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.

bimbom22
  • 4,510
  • 2
  • 31
  • 46
1

It's a coding style recommendation for novices. PHP eats up a single \n after the closing tag. Yet many newcomers inadvertently leave extra spaces or tabs or multiple newlines there. On Windows this is compounded by having a \r\n trail the ?> closing tag, which leads to isses as soon as scripts get deployed to Unix servers.

Leaving out the closing tag is also conceived as optimization by some (like single quotes).

mario
  • 144,265
  • 20
  • 237
  • 291