Why include __DIR__ in require_once?

For example, I always see autoloaders called like this:

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

What is the difference between this and more concise

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

?

+7
php autoloader
source share
2 answers

PHP scripts work relative to the current path (result of getcwd() ), and not along the path of their own file. Using __DIR__ forces you to include include 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 as follows:

 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 incorrect for file2.php , so file3.php cannot be included.

+11
source share

To enable it, you can install several folders where PHP searches automatically. When you include a file with a relative path that you are viewing in all of these folders. It is better to determine the real path to prevent some errors when downloading the wrong files.

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

Then you can be sure to upload the correct file.

0
source share

All Articles