详解PHP中include和require的区别
1.报错 include引入文件时,如果遇到错误,会报出Warning,并继续执行后面的代码; require引入文件时,如果遇到错误,会报出Error,并停止运行后面的代码。
举例说明,创建两个名为 test-include.php 和 test-require.php 的PHP文件, 注意相同的目录中,不要存在一个名字是test-nothing.php的文件。 test-include.php
<?php
include 'test-nothing.php'; //包含一个不存在的文件
echo 'abc';
?>
test-require.php
<?php
require 'test-nothing.php'; //包含一个不存在的文件
echo 'abc';
?>
浏览http://localhost/test-include.php时,因为没有找到test-nothing.php文件, 会看到类似于下面的Warning信息。同时,报错信息的下边正常显示了abc这个字符串: Warning: include(test-nothing.php) [function.include]: failed to open stream: No such file or directory in D:\www\test-include.php on line 2
Warning: include() [function.include]: Failed opening ‘test-nothing.php’ for inclusion (include_path=’.;C:\php5\pear’) in D:\www\test-include.php on line 2 abc
浏览http://localhost/test-require.php时,因为没有找到test-nothing.php文件, 我们看到了Fatal error报错信息。但是,报错信息的下边没有显示字符串abc: Warning: require(test-nothing.php) [function.require]: failed to open stream: No such file or directory in D:\www\test-require.php on line 2
Fatal error: require() [function.require]: Failed opening required ‘test-nothing’ (include_path=’.;C:\php5\pear’) in D:\www\test-require.php on line 2
2.条件引用 include是有条件包含函数; require是无条件包含函数。
例如下面例子,如果变量$somg为真,则将包含文件somefile.php:
if($some) {
include 'somefile.php';
}
但无论$some取何值,下面的代码将把文件somefile.php包含进文件里:
if($something) {
require 'somefile.php';
}
下面的例子充分说明了这两个函数之间的不同
$i = 1;
while($i < 3) {
require "somefile.$i.php";
$i++;
}
可以从以上这段代码中看出,每一次循环的时候,程序都将把同一个文件包含进去, 很显然这不我们想要的,可以看出这段代码希望在每次循环时, 将不同的文件包含进来,如果要完成这个功能,只能使用include来实现。
$i = 1;
while($i < 3) {
include "somefile.$i.php";
$i++;
}
3.文件引用方式 include执行时所引用的文件,每次都要进行读取和评估; require执行时所引用的文件,只处理一次(实际上执行时所引用的文件内容替换了require命令)。
可以看出若有包含这些指令之一的代码和可能执行多次的代码,则使用require效率比较高, 若每次执行代码时将读取不同的文件或者有通过一组文件叠代的循环,就使用include。
相关文章
- 痞子衡嵌入式:我被邀请做贸泽电子&与非网联合推出的《对话工程师》节目嘉宾
- 痞子衡嵌入式:存储器大厂Micron的NOR Flash芯片特殊丝印设计(FBGA代码)
- 痞子衡嵌入式:国内外串行NOR Flash厂商官网Cross Reference功能使用体验
- 痞子衡嵌入式:MCUXpresso IDE下高度灵活的FreeMarker链接文件模板机制
- 《痞子衡嵌入式半月刊》 第 67 期
- 《痞子衡嵌入式半月刊》 第 66 期
- 《痞子衡嵌入式半月刊》 第 65 期
- 痞子衡嵌入式:i.MXRT中FlexSPI外设不常用的读选通采样时钟源 - loopbackFromSckPad
- 痞子衡嵌入式:RT-MFB - 一种灵活的i.MXRT下多串行NOR Flash型号选择的量产方案
- 《痞子衡嵌入式半月刊》 第 64 期
- 痞子衡嵌入式:浅谈i.MXRT10xx系列MCU外接24MHz晶振的作用
- 痞子衡嵌入式:一个关于Segger J-Flash在Micron Flash固定区域下载校验失败的故事(SR寄存器BP[x:0]位)
- 痞子衡嵌入式:MCUXpresso IDE下生成镜像文件的方法及其与IAR,MDK差异
- 《痞子衡嵌入式半月刊》 第 63 期
- 《痞子衡嵌入式半月刊》 第 62 期
- 痞子衡嵌入式:理解i.MXRT中FlexSPI外设lookupTable里配置访问行列混合寻址Memory的参数值
- 《痞子衡嵌入式半月刊》 第 61 期
- 痞子衡嵌入式:在i.MXRT启动头FDCB里使能串行NOR Flash的QPI/OPI模式
- 痞子衡嵌入式:MCUXpresso IDE下设置代码编译优化等级的几种方法
- 痞子衡嵌入式:浅析IAR下调试信息输出机制之半主机(Semihosting)