PHP中include与require有什么区别
发布时间:2021-01-13 15:24:31
来源:亿速云
阅读:81
作者:Leah
PHP中include与require有什么区别?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
先编辑command.php文件echo 'hello'.PHP_EOL;
然后编辑console.php文件for($i=1;$i<=3;++$i){
require 'command1.php';
}
原本想要包含并执行这个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 '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改为includefor($i=1;$i<=3;++$i){
include 'command1.php';
}
会报出这样的错误: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。
看完上述内容,你们掌握PHP中include与require有什么区别的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!