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

开发技术 作者: 2024-08-17 12:25:01
网上太多关于PHP中include与require区别。然而事实真的如此吗,今天我们就通过一个具体的实例来简单分析验证下

先编辑command.PHP文件

然后编辑console.PHP文件

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

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

会报出这样的错误:

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.jiecseo.com/news/show_63784.html