嵌套的“include()”指令-如何从多个目录中包含一个文件(包括另一个)


Nested `include()` directives - How to include a file (which includes another) from more than one directories?

我有以下三个文件可供使用:

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文件。

这个问题的原因是什么
我该怎么修?

任何帮助都将不胜感激。

此问题的原因是,include基于工作目录来解析相对文件名,而不是基于执行include的文件所在的目录。

工作目录是Web服务器启动的PHP文件的目录(在您的情况下,我想是index.php)。如果该文件包含其他文件,则工作目录不会更改。它可以使用chdir手动更改,但不应该仅仅为了include而更改。

一种可能的解决方案是使用

include dirname(__FILE__) . DIRECTORY_SEPARATOR . '[RELATIVE_PATH]';

其中CCD_ 20是从进行包括的文件到被包括的文件的相对路径。

在PHP 5.3中,可以使用__DIR__来代替dirname(__FILE__)