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

yipeiwu_com5年前PHP代码库

先编辑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。

相关文章

PHP 使用二进制保存用户状态的实例

前言 用户状态保存是一个很常见的需求,一般用来保存用户状态的方式是在数据库表中创建多个字段来存储相应的用户状态,比如要保存用户是否绑定了手机号和QQ,则需要2个字段(mobile,qq)...

php动态读取数据清除最右边距的方法

php动态读取数据清除最右边距的方法

需求效果一行3栏: 场景模拟:同事给了我这么一段静态代码如下: <!DOCTYPE html> <html lang="en"> <head>...

php session_start()关于Cannot send session cache limiter - headers already sent错误解决方法

说是已经有输出,用编辑器打,前面明明什么都没有,原来在使用AJAX的 时候,也出现过这种情况,后来,把这个PHP文件放到linux中打开,会发现,在文件的最前面,会出现“锘 ”这样的一个...

PDO防注入原理分析以及使用PDO的注意事项总结

PDO防注入原理分析以及使用PDO的注意事项总结

本文详细讲述了PDO防注入原理分析以及使用PDO的注意事项,分享给大家供大家参考。具体分析如下: 我们都知道,只要合理正确使用PDO,可以基本上防止SQL注入的产生,本文主要回答以下两个...

PHP类继承 extends使用介绍

出来工作这么久了,项目经验倒是不少,但是当问及底层的东西时候,常常是一言不发了。现在项目设计底层的东西越来越少,可以说是真正用到的也就是那么一点,真正核心的东西都已经被框架封装好了。总感...