嵌套 `include()` 指令 - 如何包含多个目录中的文件(其中包含另一个文件)?
我有这三个文件可以使用:
document_root/include/config.php
document_root/include/database.php
document_root/index.php
文件内容的相关部分如下所示:
config.php
// ...
$MyVar = 100;
// ...
database.php
// ...
require('config.php');
// Aiming to use the definitions in "config.php" here
// ...
index.php问题
// ...
require('include/database.php');
// Using the code in "database.php" here
// ...
在于,config.php
不知何故未包含在内,但没有给出错误消息(在 E_ALL 模式下)。在运行 index.php
中的代码时,我无法从 database.php
文件访问 config.php
文件中的定义。
在我的 PHP.ini
文件中,include_path
设置为 C:\...\document_root\include
目录。
PHP 版本是 5.3.0。
我观察到,如果我将 database.php
中的 require()
指令更改为require('include/config.php');
代码运行没有任何失败,一切都很好。但这个解决方案在实践中是不可能的,因为我计划从多个位置包含 config.php 文件。
造成这个问题的原因是什么?
我该如何修复它?
任何帮助将不胜感激。
I have these three files to work with:
document_root/include/config.php
document_root/include/database.php
document_root/index.php
And the relevant part of the file contents are like below:
config.php
// ...
$MyVar = 100;
// ...
database.php
// ...
require('config.php');
// Aiming to use the definitions in "config.php" here
// ...
index.php
// ...
require('include/database.php');
// Using the code in "database.php" here
// ...
The problem is that, config.php
is somehow not included, and yet no error message is given (in E_ALL mode). I can't access to the definitions in the config.php
file from database.php
file while running the code in index.php
.
In my PHP.ini
file include_path
is set to C:\...\document_root\include
directory.
An PHP version is 5.3.0.
I have observed that, if I change the require()
directive in database.php
asrequire('include/config.php');
the code runs without any failure and everything is just fine. But this solution is not possible in practice, because I'm planing to include the config.php
file from multiple locations.
What is the cause of this problem?
How can I fix it?
Any help will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
造成此问题的原因是,
include
根据工作目录解析相对文件名,而不是基于执行include< 的文件所在的目录/代码>。
工作目录是由网络服务器启动的 PHP 文件的目录(在你的例子中我猜是
index.php
)。如果该文件包含其他文件,则工作目录不会更改。可以使用chdir
手动更改它,但是您不应该仅仅为了include
而这样做。一种可能的解决方案是使用
其中
[RELATIVE_PATH]
是执行包含的文件到所包含的文件的相对路径。在 PHP 5.3 中,可以使用
__DIR__
代替dirname(__FILE__)
。The cause of this problem is, that
include
resolves relative filenames based on the working directory, not based on the directory where the file is located that does theinclude
.The working directory is the directory of the PHP file that is launched by the webserver (in your case
index.php
I guess). If that file includes some other file, the working directory is not changed. It can be changed manually usingchdir
, but you should not do that solely for the sake of aninclude
.One possible solution is to use
where
[RELATIVE_PATH]
is the relative path from the file that does the include to the file that is included.In PHP 5.3,
__DIR__
can be used instead ofdirname(__FILE__)
.