【发布时间】:2015-02-12 17:59:03
【问题描述】:
我在相对包含文件时遇到了一些问题。问题不在于 require_once 找不到文件,而是它可以在没有文件的地方找到文件。我已将问题简化为三个小类。
这是我的目录结构:
public_html/
index.php
commands/
CommandFactory.php
account/
Status.php
index.php:
require_once 'commands/CommandFactory.php';
$factory = new CommandFactory();
CommandFactory.php:
class CommandFactory{
public function __construct()
{
echo getcwd() . '<br/>'; //xxx\public_html (which is good, this is where index.php is
//require_once 'account/Status.php'; // This works as expected
require_once 'account/Status.php'; // This ALSO works, but it shouldn't
$status = new Status(); // This works, though it shouldn't.
}
}
我已经通过将 CommandFactory 移动到不同的目录进行了测试,这解决了问题。但是,我不明白为什么可以包含该文件。它不应该包括相对于 CommandFactory 的 Status,它应该是相对于 index.php 的。我添加了当前的工作目录,看看出了什么问题,但我无法弄清楚。有谁知道这是如何以及为什么起作用的?
【问题讨论】:
-
对我的问题投反对票的人能解释一下原因吗?
-
如果你要求路径是相对于当前文件的。不是索引,无论如何在类中包含文件实际上不是一个好习惯。你绝对应该考虑自动加载你的类
-
"如果你要求路径是相对于当前文件的。"这是不对的。”而且我知道我在 OOP 中在做什么。另外,如果它是相对于当前文件,为什么“commands/account/Status.php”也可以工作?
-
Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal errorsource -
该死的,你是对的。我希望我能早点看到。你应该回答这个问题,所以我可以接受它:) 感谢您提到自动加载类。我知道何时以及为什么要使用它们,这不在我当前的项目中(我总是在类之外 require_once,除了这个,因为我正在加载的类是动态的),但其他人可能会觉得它很有趣。
标签: php include-path require-once set-include-path