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';
?
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.
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.
__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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With