[php]include()和require()区别【学习笔记】

php-include()和require()的区别

测试环境-php5.4.16

包含文件路径错误时

测试代码

  • include
<?php
    include "errorPath.php";

    echo "run to here";
?>
  • require
<?php
    require "errorPath.php";

    echo "run to here";
?>

运行结果对比

  • include
( ! ) Warning: include(errorPath.php): failed to open stream: No such file or directory in C:\wamp\www\API\index.php on line 21
Call Stack
#   Time    Memory  Function    Location
1   0.0008  142072  {main}( )   ..\index.php:0

( ! ) Warning: include(): Failed opening 'errorPath.php' for inclusion (include_path='.;C:\php\pear') in C:\wamp\www\API\index.php on line 21
Call Stack
#   Time    Memory  Function    Location
1   0.0008  142072  {main}( )   ..\index.php:0
run to here
  • require
( ! ) Warning: require(errorPath.php): failed to open stream: No such file or directory in C:\wamp\www\API\index.php on line 21
Call Stack
#   Time    Memory  Function    Location
1   0.0005  142072  {main}( )   ..\index.php:0

( ! ) Fatal error: require(): Failed opening required 'errorPath.php' (include_path='.;C:\php\pear') in C:\wamp\www\API\index.php on line 21
Call Stack
#   Time    Memory  Function    Location
1   0.0005  142072  {main}( )   ..\index.php:0

对比之后可以发现,当包含文件时发生错误

include会报错并继续下面代码的运行

require会报错并终止下面代码的运行


在网上翻阅资料时,发现的一种说法

inlcude是有条件的进行文件的包含

require是无条件将文件内容包含在当前文件,即将require语句直接替换成文件的内容

做了以下的测试

echo "php_version:".PHP_VERSION."<br>";

$i = 1; 
while ($i <= 3) {
    include "testFile/file$i.php";
    $i++; 
}

echo "<br>";

$i = 1; 
while ($i <= 3) {
    require "testFile/file$i.php";
    $i++; 
}

文件目录

  • index.php
    • testFile
      • file1.php
      • file2.php
      • file3.php

文件内容依次为”file one”、”file two”······

运行结果

php_version:5.4.16
file one 
file two

file one 
file two
结论

requireinclude并没有上述的包含文件的特性,至少在5.0+版本后是这样的

查帮助文档
include

(PHP 4, PHP 5)

include 语句包含并运行指定文件。 

以下文档也适用于 require。 

被包含文件先按参数给出的路径寻找,如果没有给出目录(只有文件名)时则按照 include_path 指定的目录寻找。如果在 include_path 下没找到该文件则 include 最后才在调用脚本文件所在的目录和当前工作目录下寻找。如果最后仍未找到文件则 include 结构会发出一条警告;这一点和 require 不同,后者会发出一个致命错误。 

如果定义了路径——不管是绝对路径(在 Windows 下以盘符或者 \ 开头,在 Unix/Linux 下以 / 开头)还是当前目录的相对路径(以 . 或者 .. 开头)——include_path 都会被完全忽略。例如一个文件以 ../ 开头,则解析器会在当前目录的父目录下寻找该文件。 

有关 PHP 怎样处理包含文件和包含路径的更多信息参见 include_path 部分的文档。 

当一个文件被包含时,其中所包含的代码继承了 include 所在行的变量范围。从该处开始,调用文件在该行处可用的任何变量在被调用的文件中也都可用。不过所有在包含文件中定义的函数和类都具有全局作用域

//-----------------------------------------------------------------------
require

(PHP 4, PHP 5)

requireinclude 几乎完全一样,除了处理失败的方式不同之外。 require 在出错时产生 E_COMPILE_ERROR 级别的错误。换句话说将导致脚本中止而 include 只产生警告(E_WARNING),脚本会继续运行。 

参见 include 文档了解详情。 

可以发现require和include除了处理失败的方式不同之外,并没有其他的不同

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值