时间:2021-07-01 10:21:17 帮助过:21人阅读
作者:zhanhailiang 日期:2013-03-19
include(),require()语句包含并运行指定文件。 这两种结构除了在如何处理失败之外完全一样。
include()产生一个警告而require()则导致一个致命错误。换句话说,如果想在遇到丢失文件时停止处理页面就用 require()。include()就不是这样,脚本会继续运行
例1:include()产生一个Warning而require()则导致一个Fatal error。
zhanhailiang@linux-06bq:~> php -r "include('a.php');" Warning: include(a.php): failed to open stream: No such file or directory in Command line code on line 1 Warning: include(): Failed opening 'a.php' for inclusion (include_path='.:/usr/local/services/phplib/src:/usr/local/services/phplib/inc:/usr/local/services/php/lib/php') in Command line code on line 1 zhanhailiang@linux-06bq:~> php -r "require('a.php');" Warning: require(a.php): failed to open stream: No such file or directory in Command line code on line 1 Fatal error: require(): Failed opening required 'a.php' (include_path='.:/usr/local/services/phplib/src:/usr/local/services/phplib/inc:/usr/local/services/php/lib/php') in Command line code on line 1
include_once()语句在脚本执行期间包含并运行指定文件。此行为和include()语句类似,唯一区别是如果该文件中的代码已经被包含了,则不会再次包含。如同此语句名字暗示的那样,只会包含一次。
include_once()应该用于在脚本执行期间同一个文件有可能被包含超过一次的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题。
返回值和include()相同。如果文件已被包含,本函数返回TRUE。
例1:include()会多次包含指定文件,而include_once()不会。
zhanhailiang@linux-06bq:~> cat a.php <?php echo '1'.PHP_EOL; zhanhailiang@linux-06bq:~> php -r "include('a.php');include('a.php');" 1 1 zhanhailiang@linux-06bq:~> php -r "include_once('a.php');include_once('a.php');" 1
例2:include_once()避免函数重定义。
zhanhailiang@linux-06bq:~> cat a.php <?php echo '1'.PHP_EOL; function test() {} zhanhailiang@linux-06bq:~> php -r "include('a.php');include('a.php');" 1 Fatal error: Cannot redeclare test() (previously declared in /home/zhanhailiang/a.php:4) in /home/zhanhailiang/a.php on line 4 zhanhailiang@linux-06bq:~> php -r "include_once('a.php');include_once('a.php');" 1