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获得客户端浏览器名称及版本的方法(基于ECShop函数)

php获得客户端浏览器名称及版本的方法(基于ECShop函数)

本文实例讲述了php获得客户端浏览器名称及版本的方法。分享给大家供大家参考,具体如下: 看到ecshop中有这么一个函数get_user_browser(),获取浏览器的名称和版本。虽然...

PHP简单选择排序算法实例

简单的选择排序算法:通过n-i次关键字间的比较,从n-i+1个记录中选出关键字最小的记录,并和第i(1<=i<=n)个记录交换 复制代码 代码如下: <?php...

php的数组与字符串的转换函数整理汇总

1.将一个字符串转化为数组str_split()用于将一个字符串转化为数组语法:复制代码 代码如下:str_split(string,length)<SPAN style="COL...

phpmyadmin安装时提示:Warning: require_once(./libraries/common.inc.php)错误解决办法

比较简洁的方法:新建一个目录将phpmyadmin中的文件复制到这个目录中,iis中设置一下路径。 安装好PHPmyAdmin后,在IE里访问时会出现下面的这种错误: Warning:...

PHP实现执行外部程序的方法详解

PHP实现执行外部程序的方法详解

本文实例讲述了PHP实现执行外部程序的方法。分享给大家供大家参考,具体如下: 在一些特殊情况下,会使用PHP调用外部程序执行,比如:调用shell命令、shell脚本、可执行程序等等,今...