为什么在 require_once 中包含 __DIR__? [英] Why include __DIR__ in the require_once?
问题描述
例如,我总是看到这样的自动加载器:
For example, I always see autoloaders called like this:
require_once __DIR__ . '/../vendor/autoload.php';
那个和更简洁的有什么区别
What is the difference between that and the more concise
require_once '../vendor/autoload.php';
?
推荐答案
PHP 脚本相对于当前路径(getcwd()
的结果)运行,而不是相对于它们自己文件的路径.使用 __DIR__
强制包含相对于它们自己的路径发生.
PHP scripts run relative to the current path (result of getcwd()
), not to the path of their own file. Using __DIR__
forces the include to happen relative to their own path.
为了演示,创建以下文件(和目录):
To demonstrate, create the following files (and directories):
- file1.php
- dir/
- file2.php
- file3.php
如果 file2.php
包含 file3.php
像这样:
If file2.php
includes file3.php
like this:
include `file3.php`.
如果你直接调用file2.php
,它会工作得很好.但是,如果 file1.php
includes file2.php
,则当前目录 (getcwd()
) 将是file2.php
错误,所以不能包含 file3.php
.
It will work fine if you call file2.php
directly. However, if file1.php
includes file2.php
, the current directory (getcwd()
), will be wrong for file2.php
, so file3.php
cannot be included.
这篇关于为什么在 require_once 中包含 __DIR__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!