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 Extension的开发——基础篇第1/2页

浅谈PHP Extension的开发——基础篇第1/2页

摘要&引言 PHP是当前应用非常广泛的一门语言,从国外的Facebook、Twitter到国内的淘宝、腾讯、百度再到互联网上林林总总的各种大中小型网站都能见到它的身影。PHP的成功,应该...

PHP垃圾回收机制引用计数器概念分析

如果你安装了xdebug,就可以用xdebug_debug_zval()显示“zval”的信息了。如下: 复制代码 代码如下:<?php$str = "jb51.net";xdeb...

php打印输出棋盘的实现方法

本文实例讲述了php打印输出棋盘的两种实现方法。分享给大家供大家参考。具体实现方法如下: 例子1,代码如下: 复制代码 代码如下:<?php /**  * 隔...

php函数与传递参数实例分析

本文实例讲述了函数的调用与函数定义语法,并讲解了关于函数中的变量以及向函数传递数值方法.分享给大家供大家参考。具体如下: 一、函数的基础 php提供了大量的函数,并且允许用户自定函数,p...

php里array_work用法实例分析

本文实例讲述了php里array_work用法。分享给大家供大家参考。具体如下: // the test array $array = array( 'php', 'array...