PHP:include和file_exists范围

时间:2014-01-02 03:34:59

标签: php include file-exists

我有一个以下目录结构:
一个文件夹“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 bug?

如果我将“conf.php”放入根目录(与“index.php”一起),

file_exists()将返回“true”。似乎include正在使用“Test.php”的范围,而“file_exists()”正在使用创建Test对象的文件的范围(在我的情况下在根目录中)。什么是正确的行为?

(使用PHP 5.5.7 Fast-CGI)

1 个答案:

答案 0 :(得分:0)

试试这个:

<?php
class Test {

  public function __construct(){
    var_dump(file_exists( __DIR__ . "/conf.php"));
    $conf = include( __DIR__ . "/conf.php");
    echo $conf;
  }

}

使用魔术常量__DIR__将返回其使用的脚本的绝对路径,而不是包含它的脚本,因此任何文件名引用都将是文件的完整路径,而不仅仅是相对路径,它使用主要运行脚本的位置。

相关问题