我有以下三个文件可供使用:
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__)
。