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中养成7个面向对象的好习惯

如果您尚未打算用 OO 原则创建应用程序,则使用 PHP 的面向对象(OO)的语言特性,这 7 个习惯将帮助您开始在过程编程与 OO 编程之间进行转换。 在 PHP 编程早期,PHP 代...

浅析PHP Socket技术

phpsocketSocket位于TCP/IP协议的传输控制协议,提供客户-服务器模式的异步通信,即客户向服务器发出服务请求,服务器接收到请求后,提供相应的反馈或服务!我练习了一个最基本...

php选择排序法实现数组排序实例分析

本文实例分析了php选择排序法实现数组排序的方法。分享给大家供大家参考。具体分析如下: 选择排序法的基本思路:直接用案例来说明吧,比如有一个数组$arr = array(2,6,3,9)...

POST一个JSON格式的数据给Restful服务实例详解

在Android/Java平台上实现POST一个json数据: JSONObject jsonObj = new JSONObject(); jsonObj.put("usernam...

PHP APC的安装与使用详解

一、PHPAPC安装下载与解压安装包:复制代码 代码如下:wget-c http://pecl.php.net/get/APC-3.1.13.tgztar-zvxf APC-3.1.13...