【问题标题】:What is the scope of require_once in PHP?PHP 中 require_once 的范围是什么?
【发布时间】:2011-02-10 09:32:58
【问题描述】:

简单问题:require_once 的范围是全局的吗?

例如:

<?PHP

require_once('baz.php');

// do some stuff
foo ($bar);

function foo($bar) {
    require_once('baz.php');
    // do different stuff
}

?>

当调用 foo 时,它是否重新解析 baz.php? 或者它是否依赖于主 php 文件中已经需要的文件(类似于为同一个包含文件连续调用两次 require_once )?

我之前看过这个帖子,但它并没有完全回答这个问题:

Should require_once "some file.php" ; appear anywhere but the top of the file?

感谢您的帮助!

【问题讨论】:

    标签: php scope server-side-includes require-once


    【解决方案1】:

    require_once() 基本上依靠物理文件来确定它是否被包含。因此,与其说是您在其中调用 require_once() 的上下文,不如说是之前是否需要该物理文件。

    在您上面的代码中,您的 foo() 函数不会重新解析 baz.php,因为它将与之前包含在顶部的文件相同。

    但是,根据您是将其包含在 foo() 中还是将其包含在顶部,您将获得不同的结果,因为当 require_once() 成功时,范围将适用。

    【讨论】:

      【解决方案2】:

      它没有。 require_once 的跟踪适用于内部函数。 但是,以下脚本会产生错误:

      一个.php

      <?php
      require_once('b.php');
      function f() { require_once('b.php'); echo "inside function f;"; }
      ?>
      

      b.php

      <?php
      f();
      ?>
      

      因为函数 f() 未预定义为 b.php。

      【讨论】:

        【解决方案3】:

        为了更具体地回答您的问题,您第二次对该文件调用 require_once 时,它不会做任何事情,因为它已经被包含在内。

        如果您的 include 中包含函数等,那么无论如何将其包含在函数中都会遇到问题,因此范围无关紧要。如果只是定义或处理的变量,那么如果您希望再次包含它,则可以使用require 而不是require_once,从而重新定义您范围内的变量。

        【讨论】:

          【解决方案4】:

          至少在 PHP 7.3 中,require_once 具有全局范围。
          如果不是这样,x.php 和 z.php 都应该像 y.php 那样抛出错误:

          一个.php

          <?php function a() { require_once 'b.php'; b(); }
          

          b.php

          <?php function b() { debug_print_backtrace(); }
          

          x.php

          <?php
          require_once 'a.php';
          a();
          b();
          

          -->

          #0 c() called at [/var/www/b.php:2]  
          #1 b() called at [/var/www/a.php:3]  
          #0 c() called at [/var/www/a.php:4]  
          

          y.php

          <?php
          require_once 'a.php';
          b();
          

          --> 致命错误:未捕获的错误:在第 3 行调用 /var/www/y.php 中未定义的函数 b()

          z.php

          <?php
          require_once 'a.php';
          require_once 'b.php';
          b();
          

          -->

          #0 b() called at [/var/www/z.php:4]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-05-23
            • 1970-01-01
            • 2011-11-11
            • 2020-10-18
            相关资源
            最近更新 更多