服务器之家

服务器之家 > 正文

PHP中include和require的区别实例分析

时间:2021-05-17 17:06     来源/作者:编程老头

先编辑command.php文件

?
1
echo 'hello'.PHP_EOL;

然后编辑console.php文件

?
1
2
3
for($i=1;$i<=3;++$i){
    require 'command1.php';
}

原本想要包含并执行这个echo,没想到写错了文件名,如果是require,会报出这样的错误:

?
1
2
3
4
5
Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4
 
Fatal error: require(): Failed opening required 'command1.php' (include_path='.') in console.php on line 4
PHP Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Fatal error: require(): Failed opening required 'command1.php' (include_path='.') in console.php on line 4

如果把require改为include

?
1
2
3
for($i=1;$i<=3;++$i){
    include 'command1.php';
}

会报出这样的错误:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4
 
Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
 
Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4
 
Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
 
Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4
 
Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4

如果使用require_once或者include_once,只要包含路径正确,那么循环只执行一次。

总结:

使用require,如果文件没有包含成功,就会报出一个fatal error,整个程序就中止了。

使用include,如果文件没有包含成功,就会报出一个普通的warning,之后的代码仍会执行。

如果你的Web程序使用了MVC这种对文件包含强依赖的设计方法,请使用require_once。

原文链接:http://www.cnblogs.com/sweng/p/6749496.html

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部