【问题标题】:PHP: include and file_exists scopePHP:包含和 file_exists 范围
【发布时间】: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


【解决方案1】:

试试这个:

<?php
class Test {

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

}

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

【讨论】:

    猜你喜欢
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多