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下将XML转换为数组

复制代码 代码如下:// Xml 转 数组, 包括根键 function xml_to_array( $xml ) { $reg = "/<(\w+)[^>]*>([\...

php读取出一个文件夹及其子文件夹下所有文件的方法示例

本文实例讲述了php读取出一个文件夹及其子文件夹下所有文件的方法。分享给大家供大家参考,具体如下: 今天的需求要在一个文件夹中读取出这个文件夹下所有的文件,当然也包括这个文件夹下面所有的...

浅谈PHP中的&lt;&lt;&lt;运算符

PHP中提供了<<<运算符构建多行字符串序列的方法,通常称为here-document或表示为heredoc的简写。 这种方法详细表述了字符串的字面值,并在文本中保留了...

Thinkphp微信公众号支付接口

本文实例为大家分享了Thinkphp微信公众号支付接口,供大家参考,具体内容如下 第一步  先把文件夹的那两个图片 配置成一样的路径 除了域名要改 其他保持一致。 第二步&nb...

浅析php中如何在有限的内存中读取大文件

正常情况下,我们可以使用fseek来读取,好处就是不会一次性读取,以下代码只适合边取边处理的情况,不适合一次性读取一次性处理。可以用以下办法生成测试文件复制代码 代码如下:$file_h...