文件包含混淆和错误

File include confusion and errors

我有以下目录结构。

public_html
    |----------app1
    |            |---------config.php
    |            |---------index.php 
    |
    |----------app2
                 |---------import.php

app1/config.php

define('ABC', 'hello');

app1/index.php

require_once 'config.php';
echo ABC;

调用 app1/index.php 输出:

Hello

app2/import.php

require_once('../app1/index.php');

调用 app2/import.php 输出:

Notice: Use of undefined constant ABC - assumed 'ABC' in /abs/path/public_html/app1/index.php on line 10 (line echo ABC)

ABC

为什么会这样?

如何包含才能使其正常工作?

您应该阅读 documentation about include and require。相对路径总是相对于第一个调用的脚本进行解析。

因此,当您调用 app1/index.php 时,require_once('config.php') 会加载 app1/index.php,但是当您调用 app2/import.php 时,require_once('config.php') 会尝试加载不存在的app2/config.php

忠告1:在你写代码的时候提出你error reporting level,你会得到更多关于错误的线索。在这种情况下,include至少要通过通知。

建议2:如果没有充分的理由,请避免使用include,使用require_once,这将在无法加载文件时出现致命错误。

使用

require_once __DIR__ . '/config.php';

而不是require_once 'config.php';

参考:PHP file paths and magic constants

问题是您 运行 脚本 php app2/import.php 来自文件夹 public_html 而不是来自 public_html/app2
如果你这样做:

cd app2 && php import.php

一切正常!

您在 app1/index.php 中使用 require_once 'config.php'; 的示例有效,因为文件 index.phpconfig.php 位于同一目录中。
但是 app2/import.php 放置在 app1/config.php 的另一个目录中,因此在这种情况下你不能使用这种方法。

为了避免相对路径混乱,您必须在 import.php 中的路径中使用常量 __DIR__,如下所示:

<?php
require_once(__DIR__ . '/../app1/index.php');

现在您可以从 public_html 目录 运行 此脚本。