【问题标题】:What is the scope of imports in PHP?PHP中导入的范围是什么?
【发布时间】:2013-07-30 15:44:51
【问题描述】:

我的服务器上有三个文件:

foo.php
assets/bar.php
assets/qux.php

foo.php 包括bar.php,bar.php 包括qux.php。 foo.php的代码如下:

<?php
    include_once("assets/bar.php");
?>

bar.php 应该如何包含qux.php?应该使用include("qux.php") 还是include("assets/qux.php")?

【问题讨论】:

  • includes 在调用它们的范围内得到解释。
  • 你试过了吗?哪个有效?
  • 提问是获得答案的一种方式,但尝试一些实验(添加一些回声语句等等)可能会获得更好的学习体验。
  • 你应该使用include (__DIR__."/qux.php");
  • @Gordon “重复”根本不谈论路径。

标签: php include scope


【解决方案1】:

如果它们在同一个目录中,那么很简单:

include("qux.php")

【讨论】:

    【解决方案2】:

    假设您没有修改包含路径,include_once('qux.php') 应该可以正常工作。

    【讨论】:

      【解决方案3】:

      它实际上应该使用include("assets/qux.php")。包含文件的路径是动态的;在这种情况下,它取决于foo.php。

      如果您要从多个目录中包含bar.php,最好使用绝对路径。

      所以,有两种方法可以在 PHP 中“链式包含”文件:

      方式#1(动态相对路径)

      include("assets/qux.php");
      

      方式#2(绝对路径)

      $ROOT = realpath($_SERVER["DOCUMENT_ROOT"]);
      include("$ROOT/assets/qux.php");
      

      As seen here

      【讨论】:

        猜你喜欢
        • 2010-09-12
        • 1970-01-01
        • 2011-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-23
        相关资源
        最近更新 更多