使用include和require的区别实例分析
程序员文章站
2022-04-07 19:06:30
...
网上太多关于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改为include
for($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。
以上就是使用include和require的区别实例分析的详细内容,更多请关注其它相关文章!
上一篇: JavaScript面向对象设计二 构造函数模式_js面向对象
下一篇: PHP基础教程五之函数
推荐阅读
-
php 中self,this的区别和操作方法实例分析
-
PHP中cookie和session的区别实例分析
-
AngularJS的依赖注入实例分析(使用module和injector)
-
php include和require的区别深入解析
-
JavaScript中toLocaleString()和toString()的区别实例分析
-
js中apply()和call()的区别与用法实例分析
-
angularjs中使用ng-bind-html和ng-include的实例
-
PHP中include和require的使用详解
-
php使用file_get_contents(‘php://input‘)和$_POST的区别实例对比
-
php中 include 、include_once、require、require_once4个语言结构的含义和区别