PHP 中的 __DIR__ 和 dirname(__FILE__) 之间有什么区别吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2749416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:32:48  来源:igfitidea点击:

Is there any difference between __DIR__ and dirname(__FILE__) in PHP?

php

提问by user198729

It looks the same for me,but I'm not sure,

对我来说看起来一样,但我不确定,

because there are many projects that uses dirname(__FILE__).

因为有很多项目使用dirname(__FILE__).

回答by Pascal MARTIN

Their result is exactly the same; so, no difference on that.

他们的结果是完全一样的;所以,没有区别。


For example, the two following lines :


例如,以下两行:

var_dump(dirname(__FILE__));
var_dump(__DIR__);

Will both give the same output :

两者都会给出相同的输出:

string '/home/squale/developpement/tests/temp' (length=37)


But, there are at least two differences :


但是,至少有两个不同之处:

  • __DIR__only exists with PHP >= 5.3
    • which is why dirname(__FILE__)is more widely used
  • __DIR__is evaluated at compile-time, while dirname(__FILE__)means a function-call and is evaluated at execution-time
    • so, __DIR__is (or, should be)faster.
  • __DIR__仅存在于PHP >= 5.3
    • 这就是为什么dirname(__FILE__)被更广泛使用的原因
  • __DIR__在编译时求值,而dirname(__FILE__)表示函数调用并在执行时求值
    • 所以,__DIR__(或应该)更快。


As, as a reference, see the Magic constantssection of the manual (quoting):


作为参考,请参阅手册的魔术常量部分(引用)

__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.
(Added in PHP 5.3.0.)

__DIR__: 文件的目录。
如果在包含中使用,则返回包含文件的目录。
这相当于 dirname(__FILE__).
除非它是根目录,否则此目录名称没有尾部斜杠。
(在 PHP 5.3.0 中添加。)