【发布时间】:2014-01-19 11:41:42
【问题描述】:
我有以下目录结构:
一个文件夹“class”,其中包含“Test.php”和“conf.php”,根目录中有一个“index.php”文件:
/
index.php
class
Test.php
conf.php
Test.php的内容是:
<?php
class Test {
public function __construct(){
var_dump(file_exists("conf.php"));
$conf = include("conf.php");
echo $conf;
}
}
“index.php”有以下内容:(只是想实例化一个新的Test类)
<?php
include "class/Test.php";
$Test = new Test();
而文件“conf.php”只包含这个:
<?php
return "Included file";
运行此代码后,我看到以下输出:
bool false
"Included file"
如您所见,“Test”对象可以包含其本地“conf.php”文件并显示其输出, 但 file_exists() 什么也没看到。我不明白为什么。 也许这是一个php错误?
file_exists() 如果我将“conf.php”放入根目录(与“index.php”一起),则返回“true”。似乎 include 正在使用“Test.php”的范围,而“file_exists()”正在使用创建 Test 对象的文件的范围(在我的例子中是根)。正确的行为是什么?
(使用 PHP 5.5.7 Fast-CGI)
【问题讨论】:
-
当您在没有完整路径的情况下调用
file_exists()时,它会从主脚本的位置进行检查,而不是从包含函数调用的脚本的位置进行检查。因此,如果您包含来自index.php的Test.php,则file_exists()将在父目录中查找conf.php,但它并不存在。您必须将其视为包含将所有代码拉入该脚本,因此所有内容都与该位置相关。您可以在包含的文件中使用__DIR__来获取实际包含文件的路径。 -
include和require使用include_path,但file_exists()和其他文件系统函数需要真实的文件路径。从根目录中,conf.php未作为相对路径找到。
标签: php include file-exists