PHP中include和require的区别实例分析
程序员文章站
2024-03-12 20:28:26
先编辑command.php文件
echo 'hello'.php_eol;
然后编辑console.php文件
for($i=1;$i<...
先编辑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。
上一篇: 几个有意思的题目
下一篇: Java之递归求和的两种简单方法(推荐)
推荐阅读
-
PHP中include和require的区别实例分析
-
PHP4和PHP5版本下解析XML文档的操作方法实例分析
-
PHP中$GLOBALS['HTTP_RAW_POST_DATA']和$_POST的区别分析
-
浅谈PHP中new self()和new static()的区别
-
PHP中$GLOBALS['HTTP_RAW_POST_DATA']和$_POST的区别分析
-
浅谈PHP中new self()和new static()的区别
-
PHP4和PHP5版本下解析XML文档的操作方法实例分析
-
PHP中include和require的区别实例分析
-
ASP.NET中Application和Cache的区别分析
-
php使用include 和require引入文件的区别