As asked in the title, whats the difference between
require(__DIR__ . '/file.php')
and
require('file.php')
?
(when both files are in the same folder)
Thank you all for your help!
?> 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.
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.
include() Vs require() The only difference is that the include() statement generates a PHP alert but allows script execution to proceed if the file to be included cannot be found. At the same time, the require() statement generates a fatal error and terminates the script.
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.
If you do
require(__DIR__ . '/file.php')
then you are requiring the file with the full pathname. If the file doing this require is required by another file in another directory, this require will always work. On the other hand, if you
require('file.php')
then if the file where this require statement is is required by another file in another directory, this statement will fail.
That is why it is generally good practice to include the __DIR__
.
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