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

yipeiwu_com6年前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获取图片信息的方法详解

本文实例讲述了php获取图片信息的方法。分享给大家供大家参考,具体如下: getimagesize() 函数将测定任何 GIF,JPG,PNG,SWF,SWC,PSD,TIFF,BMP,...

PHP设计模式之单例模式定义与用法分析

本文实例分析了PHP设计模式之单例模式。分享给大家供大家参考,具体如下: 单例模式(Singleton Pattern 单件模式或单元素模式),是常见的一种设计模式,它有三个特点...

PHP代码维护,重构变困难的4种原因分析

本文分析讲述了PHP代码维护,重构变困难的4种原因。分享给大家供大家参考,具体如下: 代码维护,重构是件很令人不爽的一件事。以下几种情况,会让代码维护和重构变得很困难。 1. 项目开始时...

解析zend studio中直接导入svn中的项目的方法步骤

1.在zend-studio中的项目explorer中右键-》import->选择svn->project from svn-》next-》选择create new ...l...

在PHP中使用redis

在Mac OS上安装redis首先是安装,它会默认安装到/usr/local/bin下复制代码 代码如下:cd /tmpwget http://redis.googlecode.com/...