首页  >  文章  >  后端开发  >  PHP中include和require的区别实例详解

PHP中include和require的区别实例详解

墨辰丷
墨辰丷原创
2018-05-22 16:13:171350浏览

网上太多关于PHP中include与require区别。然而事实真的如此吗,今天我们就通过一个具体的实例来简单分析验证下

先编辑command.php文件

echo 'hello'.PHP_EOL;

然后编辑console.php文件

for($i=1;$i<=3;++$i){
	require &#39;command1.php&#39;;
}

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

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 &#39;command1.php&#39; (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; (include_path=&#39;.&#39;) in console.php on line 4

如果把require改为include

for($i=1;$i<=3;++$i){
	include &#39;command1.php&#39;;
}

会报出这样的错误:

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

Warning: include(): Failed opening &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) in console.php on line 4

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

总结:

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

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

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

相关推荐:

详细讲解php中require,include,use区分

关于PHP Include 文件的讲解

PHP基础学习之包含require,include 

以上是PHP中include和require的区别实例详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn