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

Php

Php Problem Overview


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

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

Php Solutions


Solution 1 - Php

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.


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.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser198729View Question on Stackoverflow
Solution 1 - PhpPascal MARTINView Answer on Stackoverflow