![](/img/trans.png)
[英]PHP document does not see the "require_once __DIR__ . '/composer/autoload_real.php';"
[英]Why include __DIR__ in the require_once?
例如,我总是看到像这样调用自动加载器:
require_once __DIR__ . '/../vendor/autoload.php';
那和更简洁有什么区别
require_once '../vendor/autoload.php';
?
PHP 脚本相对于当前路径( getcwd()
结果)运行,而不是相对于它们自己文件的路径。 使用__DIR__
强制包含相对于它们自己的路径发生。
为了演示,创建以下文件(和目录):
- file1.php
- dir/
- file2.php
- file3.php
如果file2.php
包含file3.php
像这样:
include `file3.php`.
如果您直接调用file2.php
它将工作正常。 但是,如果file1.php
包含file2.php
,则当前目录( getcwd()
)对于file2.php
将是错误的,因此无法包含file3.php
。
当前接受的答案并没有完全解释使用__DIR__
的原因,在我看来答案是错误的。 我将解释为什么我们真的需要这个。 假设我们有这样的文件结构
- index.php
- file3.php -(content: hello fake world)
- dir/
- file2.php
- file3.php - (content: hello world)
如果我们从 file2.php 中包含 file3.php 并直接运行 file2.php,我们将看到输出hello world
。 现在,当我们在 index.php 中包含 file2.php 时,当代码开始执行时,它将再次看到 file2 使用include 'file3.php'
包含 file3,首先执行将在当前执行目录中查找 file3(这是存在 index.php 的同一目录)。由于 file3.php 存在于该目录中,它将包含file3.php
而不是dir/file3.php
,我们将看到输出hello fake world
而不是hello world
。
如果 file3.php 不存在于同一目录中,那么它将包含正确的dir/file3.php
文件,这使得接受的答案无效,因为它指出file3.php cannot be included
,这是不正确的。 它包括在内。
但是,这里有必要使用__DIR__
。 如果我们使用include __DIR__ . '/file3.php'
include __DIR__ . '/file3.php'
在 file2.php 中,那么即使父目录中存在另一个 file3.php,它也会包含正确的文件。
对于 include 可以设置一些 PHP 自动搜索的文件夹。 当您包含具有相对路径的文件时,您将在所有文件夹中进行搜索。 最好定义真实路径,以防止加载错误文件时出现一些错误。
https://secure.php.net/manual/en/function.set-include-path.php
然后您可以确定您加载了正确的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.