包含时相对于文件路径的 Scandir?

Scandir relative to the path of file when included?

我在一个文件中有以下代码,该文件包含在许多其他需要此信息的页面中。

$directory_list = scandir("../packages");
$known_directories = [
  ".",
  ".."
];
$unknown_directories = $result = array_diff($directory_list, $known_directories);

当我直接打开包含这段代码的文件时,它完美运行。但是,此文件需要能够通过包含在所述文件中来向其他文件提供此信息。 scandir 似乎在相对于包含此代码的文件的路径上运行。

无论该文件包含在何处,我将如何使用包含文件的路径?

尝试将 dirname(__FILE__) 添加到 scandir 的路径中:

$directory_list = scandir(dirname(__FILE__)."/../packages");
$known_directories = [
  ".",
  ".."
];
$unknown_directories = $result = array_diff($directory_list, $known_directories);

它应该可以工作,因为 __FILE__ 被描述为 here

__FILE__ The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.

您甚至可以将 dirname(__FILE__) 替换为 __DIR__

__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.