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实现桥梁模式(bridge)

学习php设计模式 php实现桥梁模式(bridge)

一、桥梁模式结构图   二、桥梁模式中主要角色 抽象化(Abstraction)角色:定义抽象类的接口并保存一个对实现化对象的引用。 修正抽象化(Refined Abstra...

php-redis中的sort排序函数总结

很多人把redis当成一种数据库,其实是利用redis来构造数据库的模型,有那种数据库的味道。但是在怎么构建还是key和value的关系,与真正的关系型数据库还是不一样的。 效率高,不方...

PHP实现的Redis多库选择功能单例类

本文实例讲述了PHP实现的Redis多库选择功能单例类。分享给大家供大家参考,具体如下: 前言 qq群里有同学问redis如何进行多库选择,用php实现了一下,还望各位多多指点 代码...

优化WordPress中文章与评论的时间显示

很多博客都喜欢用 评论发表于 “XXX 分钟 之前”、文章发表于 “XXX 分钟 之前”来显示文章评论的时间,改善的时间显示方式不仅能很直观的告诉读者这篇文章或评论发表距今已有多长时间,...

php 获得汉字拼音首字母的函数

php获取汉字拼音的第一个字母复制代码 代码如下:<?php function getinitial($str) { $asc=ord(substr($str,0,1)); if...