In many projects I saw the connection of a third-party file in this form:
<?php include( dirname(__FILE__) . '/file.php' ); ?>
In theory, this code does the same thing:
<?php include( 'file.php' ); ?>
So what is the difference and why do programmers use the first option?
Files are included based on the path of the specified file, or if no path is specified, the path specified in the
include_pathdirective is used . If the file is not found in
includewill try to check the directory that contains the current include script and the current working directory before throwing an error.
Therefore, I see two reasons to specify an absolute path:
- Avoid surprises caused by interference with the
- Speed up work: immediately go to the absolute path, rather than sorting through directories that may be implied.
Since version 5.3, __DIR__ can be used instead of
__DIR__ In this answer they write that this can work even faster, because
__DIR__ is defined at compile time, and
dirname(__FILE__) means a function call and therefore happens at runtime.