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程序Laravel 5框架的优化技巧

Laravel是一个功能强大的框架,组件很多,代码也很庞大,它的易用方便是牺牲了性能的,即便如此它仍然是一个优秀的框架,但在正式环境下要做好优化提升网站的打开速度 接下来分享一些开发的最...

php实现给图片加灰色半透明效果的方法

本文实例讲述了php实现给图片加灰色半透明效果的方法。分享给大家供大家参考。具体实现方法如下: 原理: 1.首先计算出原图片的尺寸 2.创建相同尺寸的半透明图片 3.使用 imageco...

PHP4和PHP5性能测试和对比 测试代码与环境

作者:heiyeluren博客:http://blog.csdn.net/heiyeshuwu时间:2007年8月6日PHP 4到今年年底PHP Group将不再对其进行支持了,所以为了...

浅析PHP7的多进程及实例源码

准备 我们都知道PHP是单进程执行的,PHP处理多并发主要是依赖服务器或PHP-FPM的多进程及它们进程的复用,但PHP实现多进程也意义重大,尤其是在后台Cli模式下处理大量数据或运行...

php curl 伪造IP来源的实例代码

curl发出请求的文件fake_ip.php: 代码 复制代码 代码如下: <?php $ch = curl_init(); $url = "http://localhost/ta...