Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why include __DIR__ in the require_once?

Tags:

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'; 

?

like image 716
Dan Goodspeed Avatar asked Sep 07 '15 18:09

Dan Goodspeed


People also ask

What is the use of __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.

What is difference between include require include _ once and require _once ()?

They are all ways of including files. Require means it needs it. Require_once means it will need it but only requires it once. Include means it will include a file but it doesn't need it to continue.

What is __ FILE __ in PHP?

__FILE__ is simply the name of the current file. realpath(dirname(__FILE__)) gets the name of the directory that the file is in -- in essence, the directory that the app is installed in.

What is the use of require_once in PHP?

Definition and Usage The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.


1 Answers

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.

like image 111
Evert Avatar answered Sep 29 '22 17:09

Evert