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实现邮件群发的源码

复制代码 代码如下: <?php  // 请求 PHPmailer类 文件  require_once("class.phpmailer.php");...

php实现的简单日志写入函数

本文实例讲述了php实现的简单日志写入函数。分享给大家供大家参考。具体实现方法如下: function log( $logthis ){ file_put_contents('log...

解决phpmyadmin中文乱码问题。。。

解决phpmyadmin中文乱码问题。。。 去phpMyAdmin的根目录下,打开以下这个文件: libraries/select_lang.lib.php    1、找到有"zh-gb...

php 修改上传文件大小限制实例详解

1. 修改 max_execution_time 在php中,默认的页面最久执行时间为 30 秒,超过30秒,该脚本就停止执行. 这样就会出现无法打开网页的情况.这时我们可以修改 max...

PHP如何通过表单直接提交大文件详解

PHP如何通过表单直接提交大文件详解

前言 我想通过表单直接提交大文件,django 那边我就是这么干的。而对于 php 来说,我认为尽管可以设置最大上传的大小,但最大也无法超过内存大小,因为它无法把文件内容都放到 php:...