zoukankan      html  css  js  c++  java
  • 一个例子简要说明include和require的区别

    先编辑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。

    本文为博主原创文章,转载请在明显位置注明出处: http://www.cnblogs.com/sweng

    本作品采用知识共享署名-非商业性使用-禁止演绎 3.0 未本地化版本许可协议进行许可。

  • 相关阅读:
    Shell重新学习(忘光了)
    vim 设置默认显示行号
    maven学习资料(三)
    maven:新建的maven工程需要添加一下插件
    Spring框架:第五章:Spring EL表达式
    Spring框架:第四章:Spring管理数据库连接池
    Spring框架:第三章:对象的生命周期及单例bean生命周期的11个步骤
    Spring框架:第二章:IOC依赖注入及40个实验
    Spring框架:第一章:介绍和准备工作
    MyBatis框架:第十一章:mybatis 逆向工程
  • 原文地址:https://www.cnblogs.com/sweng/p/6749496.html
Copyright © 2011-2022 走看看