I have a following directory structure:
one folder "class" with "Test.php" and "conf.php" in it and one "index.php" file in the root:

/
index.php
class
   Test.php
   conf.php




The content of Test.php is:

<?php
class Test {

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

}




"index.php" has following contents: (Just trying to instantiate a new Test class)

<?php
include "class/Test.php";
$Test = new Test();




And the file "conf.php" contains only this:

<?php
return "Included file";

After running this code I see the following output:

bool false
"Included file"

As you can see the "Test" object can include its local "conf.php" file and show its output, but file_exists() doesn't see nothing. I don't understand why. Maybe it is a php bug?

file_exists() returns "true" if I place the "conf.php" into the root (together with "index.php"). It seems that include is using the scope of the "Test.php" and "file_exists()" is using the scope of the file where the Test object were created (in the root in my case). What is the correct behavior?

(Using PHP 5.5.7 Fast-CGI)

有帮助吗?

解决方案

Try this:

<?php
class Test {

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

}

Using the magic constant __DIR__ will return the absolute path to the script it is used, instead of the script that includes it, so any file name references will be to full path of the file, rather than just relative paths, which uses the primary running script's location.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top