I am using a php library which has this code: require_once dirname(__FILE__) . '/config.php';
From what I've read, dirname(__FILE__)
points to the current directory.
So wouldn't it be easier to just write require_once 'config.php';
?
My only guess here is that including the dirname(__FILE__)
ensures that the require_once
function uses an absolute rather than relative path.
dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap. php resides. (Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__) .)
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.
The only difference between the two is that require and its sister require_once throw a fatal error if the file is not found, whereas include and include_once only show a warning and continue to load the rest of the page.
The require() function is used to include a PHP file into another irrespective of whether the file is included before or not. The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.
Yes, you are right - dirname(__FILE__)
ensures that the require_once function uses an absolute rather than relative path.
The __FILE__
constant represents the running script. It will return the full path and file name of the running script.
For example, if a script called database.init.php
which is included from anywhere on the filesystem wants to include the script database.class.php
, which lays in the same directory, you can use:
require_once dirname(__FILE__) . '/database.class.php';
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