代码之家  ›  专栏  ›  技术社区  ›  Dan Hanly

php中“include”和“require”的区别

  •  171
  • Dan Hanly  · 技术社区  · 14 年前

    他们之间有什么区别吗?使用它们是一种偏好吗?使用一个比另一个有什么好处吗?哪个更安全?

    6 回复  |  直到 14 年前
        1
  •  150
  •   Community Tales Farias    7 年前

    您可以在上的详细PHP手册中找到这些差异 the page of require :

    要求 include 除非失败,否则也会产生致命的后果 E_COMPILE_ERROR E_WARNING )允许脚本继续。

    看到了吗 @efritz's answer

        2
  •  182
  •   Community Tales Farias    4 年前

    require 如果无法加载文件,将抛出一个PHP致命错误。(执行停止)

    include 如果无法加载文件,则生成警告。(继续执行)

    这是一个不错的 illustration of include and require difference :

    enter image description here

    发件人: Difference require vs. include php (by Robert; Nov 2012)

        3
  •  5
  •   Martin Bean    14 年前

    使用 include

    使用 require 意味着如果无法加载指定的文件,脚本将停止,并抛出致命错误。

        4
  •  3
  •   thomas    4 年前

    两者的区别 include() require() 当找不到包含的文件时发生: 包含() )剧本还会继续,但是 编译错误 需要()

    有关详细信息: Difference between Include and Require in PHP

        5
  •  2
  •   user187291    14 年前

    正如其他人指出的,唯一的区别是require抛出致命错误,而include抛出可捕获的警告。至于用哪一种,我的建议是坚持包括在内。为什么?因为您可以捕捉到警告并向最终用户提供有意义的反馈。考虑

      // Example 1.
      // users see a standard php error message or a blank screen
      // depending on your display_errors setting
      require 'not_there'; 
    
    
      // Example 2.
      // users see a meaningful error message
      try {
          include 'not_there';
      } catch(Exception $e) {
         echo "something strange happened!";
      }
    

    注意:例如2,为了工作,您需要安装一个errors to exceptions处理程序,如下所述 http://www.php.net/manual/en/class.errorexception.php

      function exception_error_handler($errno, $errstr, $errfile, $errline ) {
         throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
      }
      set_error_handler("exception_error_handler");   
    
        6
  •  0
  •   Raymond    8 年前
    <?PHP
    echo "Firstline";
    include('classes/connection.php');
    echo "I will run if include but not on Require";
    ?>
    

    一个非常简单的实用代码示例。 将显示第一个回声。无论您使用include还是require,因为它在include或required之前运行。

    要求 .

    如果你使用 要求 第二个echo不会执行,但是如果使用 包括 不管发生什么错误,你也会看到第二次回声的结果。

        7
  •  -2
  •   user2069222 user2069222    11 年前

    如果是Include,程序将不会终止并在浏览器上显示警告;另一方面,如果找不到文件,则Require程序将终止并显示致命错误。