php require_once 包含相对于文件而不是工作目录的文件

Posted

技术标签:

【中文标题】php require_once 包含相对于文件而不是工作目录的文件【英文标题】:php require_once includes files relative to file instead of working directory 【发布时间】: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 error source 该死的,你是对的。我希望我能早点看到。你应该回答这个问题,所以我可以接受它:) 感谢您提到自动加载类。我知道何时以及为什么要使用它们,这不在我当前的项目中(我总是在类之外 require_once,除了这个,因为我正在加载的类是动态的),但其他人可能会觉得它很有趣。 【参考方案1】:

来自 php.net 网站:

根据给定的文件路径包含文件,如果没有给出,则 指定的 include_path。如果文件在 include_path, include 最终会检入调用脚本自己的 目录和失败前的当前工作目录。这 如果找不到文件,include 构造将发出警告;这 与 require 的行为不同,会发出致命错误

source

【讨论】:

谢谢 :) 哈哈,不过我宁愿严格一点。 没问题。我喜欢在每次包含/要求自己强硬之前放置 DIR 好吧,因为 DIR 我认为 PHP 从来没有包含相对于相对路径的类。但我应该倾向于 php.net。

以上是关于php require_once 包含相对于文件而不是工作目录的文件的主要内容,如果未能解决你的问题,请参考以下文章

php页面中的包含文件用相对路径(require_once("./smarty/smarty.class.php"))出错了怎么解决

无法让本地主机上的 ajax 调用 require_once 工作

如何使 PHP 包含/需要组合?

PHP require_once 错误与相对路径

require与require_once有啥区别?PHP

require_once 不起作用(相对路径)