PHP中include和require的区别实例分析

5年以前  |  阅读数:751 次  |  编程语言: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分页显示制作详细讲解
SSH 登录失败:Host key verification failed
获取IMSI
将二进制数据转为16进制以便显示
获取IMEI
文件下载
贪吃蛇
双位运算符
PHP自定义函数获取搜索引擎来源关键字的方法
Java生成UUID
发送邮件
年的日历图
提取后缀名
在Zeus Web Server中安装PHP语言支持
让你成为最历害的git提交人
Yii2汉字转拼音类的实例代码
再谈PHP中单双引号的区别详解
指定应用ID以获取对应的应用名称
Python 2与Python 3版本和编码的对比
php封装的page分页类完整实例