30

For example, I always see autoloaders called like this:

require_once __DIR__ . '/../vendor/autoload.php';

What is the difference between that and the more concise

require_once '../vendor/autoload.php';

?

Dan Goodspeed
  • 3,484
  • 4
  • 26
  • 35

3 Answers3

39

PHP scripts run relative to the current path (result of getcwd()), not to the path of their own file. Using __DIR__ forces the include to happen relative to their own path.

To demonstrate, create the following files (and directories):

- file1.php
- dir/
   - file2.php
   - file3.php

If file2.php includes file3.php like this:

include `file3.php`.

It will work fine if you call file2.php directly. However, if file1.php includes file2.php, the current directory (getcwd()), will be wrong for file2.php, so file3.php cannot be included.

Evert
  • 93,428
  • 18
  • 118
  • 189
11

The current accepted answer does not fully explain the cause of using __DIR__ and in my opinion the answer is wrong. I am gonna explain why do we really need this. Suppose we have a file structure like this

- index.php
- file3.php -(content: hello fake world)
- dir/
   - file2.php
   - file3.php - (content: hello world)

If we include file3.php from file2.php and run file2.php directly, we will see the output hello world. Now when we include file2.php in index.php, when the code will start executing and it will see file2.php again including file3.php using include 'file3.php', at first the execution will look for file3.php in the current execution directory (which is the same directory where index.php is present)..Since file3.php is present in that directory, it will include that file3.php instead of dir/file3.php and we will see the output hello fake world instead of hello world.

If file3.php would not exist in the same directory, it would then include the correct dir/file3.php file which makes the accepted answer not valid because it states file3.php cannot be included which is not true. It is included.

However, here comes the necessity of using __DIR__. If we would use include __DIR__ . '/file3.php' in file2.php, then it would include the correct file even though another file3.php is present in the parent directory.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Mehbub Rashid
  • 553
  • 6
  • 6
0

For include its possible to set some folders where PHP search automatically. When you include a file with a relative path you search in all of that folders. Its better to define the real path to prevent some errors in loading wrong files.

https://secure.php.net/manual/en/function.set-include-path.php

Then you can be sure that you load the correct file.

René Höhle
  • 26,716
  • 22
  • 73
  • 82