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

时间:2021-12-06 12:05:11

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

对我来说是一样的,但我不确定,

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

因为有许多项目使用dirname(__FILE__)。

1 个解决方案

#1


162  

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
    • 这就是为什么dirname(__FILE__)被更广泛地使用的原因
  • __DIR__仅存在于PHP >= 5.3中,这就是为什么dirname(__FILE__)被更广泛地使用的原因
  • __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__是(或应该是)更快的。
  • __DIR__在编译时进行计算,而dirname(__FILE__)表示函数调用,并在执行时进行计算,因此__DIR__(或应该)更快。


As, as a reference, see the Magic constants section 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__:文件的目录。如果在include中使用,则返回包含的文件的目录。这相当于dirname(__FILE__)。这个目录名没有末尾斜杠,除非它是根目录。(添加到PHP 5.3.0。)

#1


162  

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
    • 这就是为什么dirname(__FILE__)被更广泛地使用的原因
  • __DIR__仅存在于PHP >= 5.3中,这就是为什么dirname(__FILE__)被更广泛地使用的原因
  • __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__是(或应该是)更快的。
  • __DIR__在编译时进行计算,而dirname(__FILE__)表示函数调用,并在执行时进行计算,因此__DIR__(或应该)更快。


As, as a reference, see the Magic constants section 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__:文件的目录。如果在include中使用,则返回包含的文件的目录。这相当于dirname(__FILE__)。这个目录名没有末尾斜杠,除非它是根目录。(添加到PHP 5.3.0。)