指令分隔符

同 C 或 Perl 一样,PHP 需要在每个语句后用分号结束指令。一段 PHP 代码中的结束标记隐含表示了一个分号;在一个 PHP 代码段中的最后一行可以不用分号结束。如果后面还有新行,则代码段的结束标记包含了行结束。

<?php
    
echo "This is a test";
?>

<?php echo "This is a test" ?>

<?php echo 'We omitted the last closing tag';

Note:

文件末尾的 PHP 代码段结束标记可以不要,有些情况下当使用 include 或者 require 时省略掉会更好些,这样不期望的空白符就不会出现在文件末尾,之后仍然可以输出响应标头。在使用输出缓冲时也很便利,就不会看到由包含文件生成的不期望的空白符。

User Contributed Notes

David A. Gray, MBA 14-Oct-2017 02:04
For the benefit of other beginners, it's worth noting that the brace that closes a block need not be followed by a semicolon, and, in some cases (e. g.. the closing brace of a function), it might even be a syntax error.
zored 20-Feb-2017 06:56
Semicolon examples:

<?php
echo 'Ok' ?>

<?php
echo 'Ok'
?>

<?php
echo 'Ok'

?>

<?php
echo 'Parse error'
Kalimuthu 06-Sep-2014 06:54
One thing to remember is, if you decide to omit the closing PHP tag, then the last line of the file should be ended with semi colon. If you add the closing tag then last line doesn't need to end with semi colon.

<?php
echo "First line";
echo
"Last line"

The above code throws error as it neither has closing tag nor semicolon ending. So it should be replaced with either of the below two

<?php
echo "First line";
echo
"Last line";

or

<?
php
echo "First line";
echo
"Last line" ?>
pbarney 18-Nov-2011 01:13
If you want to keep the newline after a closing tag in the output, just add a space after the closing tag, and the newline will not be ignored.
Krishna Srikanth 17-Aug-2006 01:44
Do not mis interpret

<?php echo 'Ending tag excluded';

with

<?php echo 'Ending tag excluded';
<
p>But html is still visible</p>

The second one would give error. Exclude ?> if you no more html to write after the code.