[PHP]区分include(),require(),include_once(),require_once()_PHP教程
程序员文章站
2022-04-21 17:37:56
...
1.include()与require()的区别(同理可区分include_once()与require_once())
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
2.include()与include_once()的区别(同理可区别require()与require_once())
include_once()语句在脚本执行期间包含并运行指定文件。此行为和include()语句类似,唯一区别是如果该文件中的代码已经被包含了,则不会再次包含。如同此语句名字暗示的那样,只会包含一次。
include_once()应该用于在脚本执行期间同一个文件有可能被包含超过一次的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题。
返回值和include()相同。如果文件已被包含,本函数返回TRUE。
例1:include()会多次包含指定文件,而include_once()不会。
zhanhailiang@linux-06bq:~> cat a.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 www.2cto.com
例2:include_once()避免函数重定义。
zhanhailiang@linux-06bq:~> cat a.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
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
相关文章
相关视频
推荐阅读
-
PHP包含文件函数include、include_once、require、require_once区别总结
-
php 文件包含 include、include_once、require、require_once
-
php中 include 、include_once、require、require_once4个语言结构的含义和区别
-
php include,include_once,require,require_once
-
PHP包含文件函数include、include_once、require、require_once区别总结
-
php require_once用法与相对目录要谨慎_PHP教程
-
require(),include(),require_once()和include_once()区别_php技巧
-
【php】include、include_once、require、require_once的区别【转】
-
require(),include(),require_once()和include_once()区别_php技巧
-
php中文件包含include(),require()介绍_PHP教程