例如,我总是看到这样调用的自动加载器:
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
includes file2.php
,则当前目录 (getcwd()
) 将是file2.php
错误,因此无法包含 file3.php
。
关于php - 为什么在 require_once 中包含 __DIR__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444572/