更新时间:2023-11-17 12:44:10
比方说,我有一个(伪)目录结构,如:
Let's say I have a (fake) directory structure like:
.../root/
/app
bootstrap.php
/scripts
something/
somescript.php
/public
index.php
现在假定bootstrap.php
包含一些用于建立数据库连接的代码或其他某种增强功能.
Now assume that bootstrap.php
has some code included for setting up database connections or some other kind of boostrapping stuff.
假设您要在boostrap.php
的文件夹中包含一个名为init.php
的文件.现在,为避免使用include 'init.php'
扫描整个包含路径,可以使用include './init.php'
.
Assume you want to include a file in boostrap.php
's folder called init.php
. Now, to avoid scanning the entire include path with include 'init.php'
, you could use include './init.php'
.
但是有一个问题.该./
将相对于包含bootstrap.php
而不是bootstrap.php
的脚本. (从技术上讲,它将相对于工作目录.)
There's a problem though. That ./
will be relative to the script that included bootstrap.php
, not bootstrap.php
. (Technically speaking, it will be relative to the working directory.)
dirname(__FILE__)
允许您获取绝对路径(从而避免包含路径搜索),而不必依赖工作目录作为bootstrap.php
所在的目录.
dirname(__FILE__)
allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap.php
resides.
(注意:自PHP 5.3起,您可以使用__DIR__
代替dirname(__FILE__)
.)
(Note: since PHP 5.3, you can use __DIR__
in place of dirname(__FILE__)
.)
现在,为什么不只使用include 'init.php';
?
Now, why not just use include 'init.php';
?
虽然起初很奇怪,但不能保证.
包含在包含路径中.有时为了避免无用的stat()
的人们在很少包含同一目录中的文件时将其从包含路径中删除(为什么当您知道包含不再存在时为什么要搜索当前目录?).
As odd as it is at first though, .
is not guaranteed to be in the include path. Sometimes to avoid useless stat()
's people remove it from the include path when they are rarely include files in the same directory (why search the current directory when you know includes are never going to be there?).
Note: About half of this answer is address in a rather old post: What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?