>  기사  >  백엔드 개발  >  [PHP]区分include(),require(),include_once(),require_once()_PHP教程

[PHP]区分include(),require(),include_once(),require_once()_PHP教程

WBOY
WBOY원래의
2016-07-14 10:09:36900검색

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477641.htmlTechArticle1.include()与require()的区别(同理可区分include_once()与require_once()) include(),require()语句包含并运行指定文件。 这两种结构除了在如何处理失败之外...
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.