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。

相关文章

将CMYK颜色值和RGB颜色相互转换的PHP代码

function hex2rgb($hex) { $color = str_replace('#','',$hex); $rgb = array('r' => hexdec(s...

PHP使用适合阅读的格式显示文件大小的方法

本文实例讲述了PHP使用适合阅读的格式显示文件大小的方法。分享给大家供大家参考。具体分析如下: 文件大小显示,例如 1.7K , 2.9M 代码如下: 复制代码 代码如下:// A mu...

PHP的curl实现get,post和cookie(实例介绍)

类似于dreamhost这类主机服务商,是显示fopen的使用 的。使用php的curl可以实现支持FTP、FTPS、HTTP HTPPS SCP SFTP TFTP TELNET DI...

PHP生成UTF8文件的方法

复制代码 代码如下:<?php $f=fopen("test.txt", "wb"); $text=utf8_encode("a!"); //先用函数utf8_encode将所需写...

PHP实现的sqlite数据库连接类

本文实例讲述了PHP实现的sqlite数据库连接类。分享给大家供大家参考。具体实现方法如下: 该sqlite数据库连接类就是利用了php与sqlite进行连接操作,代码如下: 复制代码...