[英]PHP: include and file_exists scope
我有以下目錄結構:
一個文件夾“ 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錯誤?
如果我將“ conf.php”放入根目錄(連同“ index.php”一起),file_exists()將返回“ true”。 似乎include使用“ Test.php”的范圍,而“ file_exists()”使用創建Test對象的文件的范圍(在我的例子中為根)。 正確的行為是什么?
(使用PHP 5.5.7 Fast-CGI)
嘗試這個:
<?php
class Test {
public function __construct(){
var_dump(file_exists( __DIR__ . "/conf.php"));
$conf = include( __DIR__ . "/conf.php");
echo $conf;
}
}
使用魔術常數__DIR__
將返回所使用腳本的絕對路徑,而不是包含它的腳本,因此任何文件名引用都將指向文件的完整路徑,而不僅僅是相對路徑,后者使用主要運行方式腳本的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.