您的位置:首页 > 编程语言 > PHP开发

省略PHP结束标记 “?>”的好处

2012-04-22 12:52 232 查看
(一) php有四种风格的标记:
    1、简短风格 <? ?>            //短标签,需在php.ini中配置 short_open_tag=on
    2、脚本风格 <script language='php'></script>
    3、标准风格 <?php ?>
    4、ASP风格 <% %>         //也需要在php.ini中配置 asp_tags=on

    (二)在Zend Framework 与 CodeIginter框架中,都没有结束标记 :“?>”,发现纯粹的php代码往往不包含结束标记 '?>'. 其原因如下:
    1、Removing it eliminates the possibility for unwanted whitespace at the end of
files which can cause "header already sent" errors, XHTML/XML validation issues, and other problems.
    2、The closing delimiter at the end of a file is optional.
    3、PHP.net itself removes the closing delimiter from the end of its files (example: prepend.inc),
so this can be seen as a "best practice."
    
    通常情况下,处于对代码的可移植性,方便性等考虑,我们使用标准风格<?php ?>.

     (三)测试
test.php



然后我们include这个文件:
test2.php



当运行test2.php时会有如下错误:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already
sent....

原因是因为test.php在结束标记之后有空行回车或空格,所以有会造成此种错误。

所以,在文件结束处,不要写多余的“?>”

特别注意:在需要使用header函数修改响应状态码时,而且也有文件相互包含的情况也不要写结束标记。

参考:http://hi.baidu.com/84923_cn/blog/item/2a45d2afc8cb14f3faed5070.html

          http://hi.baidu.com/szxiaokang/blog/item/a7f72fa8eea16ca1ca130c43.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息