包括相对路径奇怪地工作
Include relative path works strangely
我有这个文件夹和文件结构:
- public_html(文件夹)
- index.php(文件)
- 资源(文件夹)
- configs(文件夹)
- main_config.php(文件)
- render_template.php(文件)-(此文件与configs文件夹同级,在resources文件夹内)
在index.php我调用:
require_once("../resources/render_template.php");
在render_template.php我调用:
require_once("configs/main_config.php");
或者:(两者都有效)
require_once("../resources/configs/main_config.php");
我的问题:
为什么 require_once("configs/main_config.php")
有效?路径现在不需要相对于 index.php 因为 render_template.php 文件包含在 index.php 中,这意味着需要添加 ../resources/ 离开 public_html 文件夹?
如果第一种方法是正确的,为什么require_once("../resources/configs/main_config.php");
会起作用?
它的工作方式一点也不奇怪。它遵循一个逻辑模式。
- 为什么
require_once("configs/main_config.php")
有效?
之所以有效,是因为它不会根据包含此“父”文件的位置来评估相对路径。 main_config.php
包含在 render_template.php
中。它不需要知道可能包含 render_template.php
的位置。
如果它实际上取决于包含父文件的位置,那么您需要为来自不同文件夹的文件定义不同的相对路径,这显然是行不通的。它必须是通用的,以便脚本可以包含在任何需要的地方。
它是通过首先包含“最低”级别的文件来实现的。 index.php
包括 render_template.php
,其中包括 main_config.php
。这意味着在 render_template.php
内容被添加到 index.php
之前,main_config.php
内容将被添加到 render_template.php
。所以他们最终会在调用require_once("../resources/render_template.php")
的地方一起添加到index.php
。
- 如果第一种方法是正确的,为什么
require_once("../resources/configs/main_config.php");
会起作用?
没有理由不工作。如果您采用我们在第一个答案中所述的内容(它与包含“父”的位置无关),它遵循一个确切的路径:
- 我们目前位于
resources
文件夹中,位于 render_template.php
。
- 我们将上一级 (
..
) 移动到“根”文件夹(包含 public_index
和 resources
文件夹)。
- 我们移回
resources
文件夹。剩下的就简单了。
我有这个文件夹和文件结构:
- public_html(文件夹)
- index.php(文件)
- 资源(文件夹)
- configs(文件夹)
- main_config.php(文件)
- render_template.php(文件)-(此文件与configs文件夹同级,在resources文件夹内)
- configs(文件夹)
在index.php我调用:
require_once("../resources/render_template.php");
在render_template.php我调用:
require_once("configs/main_config.php");
或者:(两者都有效)
require_once("../resources/configs/main_config.php");
我的问题:
为什么
require_once("configs/main_config.php")
有效?路径现在不需要相对于 index.php 因为 render_template.php 文件包含在 index.php 中,这意味着需要添加 ../resources/ 离开 public_html 文件夹?如果第一种方法是正确的,为什么
require_once("../resources/configs/main_config.php");
会起作用?
它的工作方式一点也不奇怪。它遵循一个逻辑模式。
- 为什么
require_once("configs/main_config.php")
有效?
之所以有效,是因为它不会根据包含此“父”文件的位置来评估相对路径。 main_config.php
包含在 render_template.php
中。它不需要知道可能包含 render_template.php
的位置。
如果它实际上取决于包含父文件的位置,那么您需要为来自不同文件夹的文件定义不同的相对路径,这显然是行不通的。它必须是通用的,以便脚本可以包含在任何需要的地方。
它是通过首先包含“最低”级别的文件来实现的。 index.php
包括 render_template.php
,其中包括 main_config.php
。这意味着在 render_template.php
内容被添加到 index.php
之前,main_config.php
内容将被添加到 render_template.php
。所以他们最终会在调用require_once("../resources/render_template.php")
的地方一起添加到index.php
。
- 如果第一种方法是正确的,为什么
require_once("../resources/configs/main_config.php");
会起作用?
没有理由不工作。如果您采用我们在第一个答案中所述的内容(它与包含“父”的位置无关),它遵循一个确切的路径:
- 我们目前位于
resources
文件夹中,位于render_template.php
。 - 我们将上一级 (
..
) 移动到“根”文件夹(包含public_index
和resources
文件夹)。 - 我们移回
resources
文件夹。剩下的就简单了。