gpt4 book ai didi

php includes 有什么方法可以只包含与该文档相关的文件吗?

转载 作者:IT王子 更新时间:2023-10-29 00:09:37 25 4
gpt4 key购买 nike

如果我有一个包含 inc/footer.php 的 index.php 文件,我会这样写:

include 'inc/footer.php';

如果我想在 footer.php 中包含另一个文件,我必须相对于 index.php 文件(包含它的文件)进行操作。这可能不是问题,但如果我想从一个完全不同的位置包含 index.php 怎么办?

我知道有几种方法可以实现这一点,例如定义绝对路径或使用 dirname(__FILE__)

这从来都不是一个真正的问题,因为我总是以某种方式解决它,但我一直想知道在 php 中究竟如何包含工作。

有人可以向我解释幕后发生的事情吗?

最佳答案

这可能有帮助:(来自 http://php.net/manual/en/function.include.php)

Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/. If filename begins with ./ or ../, it is looked for only in the current working directory or parent of the current working directory, respectively

你的问题是:

If I want to include another file inside footer.php, I must do it relative to the index.php file (the one that is including it).

仅当您尝试 include() 的文件路径以 ./../ 开头时才成立。如果您需要使用相对路径在当前文件之上包含一个文件,您可以(按照您的建议)使用:

include( dirname(__FILE__) . '/../file.php')

如果定义了绝对路径,也可以在当前的include_path中加上这个:

set_include_path(get_include_path() . PATH_SEPARATOR . '/absolute/path');

然后您可以执行所有相对于“/absolute/path/”的包含。

关于php includes 有什么方法可以只包含与该文档相关的文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1031481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com