views:

425

answers:

3

Lots of famous PHP scripts including WordPress use dirname(_FILE_).'/myParent.php' instead of just 'myParent.php' when including files in the same directory of the currently running script.

Aren't they the same thing? Why do you prefer typing more?

Thanks.

+6  A: 

PHP needs to know the absolute path to the file. dirname(__FILE__).'/myParent.php' already is the absolute path but 'myParent.php' requires a lookup using the given paths in include_path to get an absolute path and find the file. A better choice would be './myParent.php':

However, it is more efficient to explicitly use include './file' than having PHP always check the current directory for every include.

Gumbo
An absolute path is not required, and the include path isn't necessarily needed. "If a path is defined (full or relative), the include_path will be ignored altogether." http://us2.php.net/manual/en/function.include.php
Justin Johnson
@Justin Johnson: With *path* the manual probably means that the string contains at least one `/`. So `./foo`, `foo/bar`, `/foo/bar` are paths but `foo` is not. And that does also apply for `myParent.php`.
Gumbo
+6  A: 

Using dirname + file name is slightly faster, because PHP will not iterate through *include_path* searching for the file. If speed matters, you will likely type more.

alexef
+4  A: 

Besides the performance increase (which is likely a pre-optimization in most cases*), it also protects from the (very odd) scenario where the environment's PHP configuration does not have the current directory (.) as part of the include path.

* Benchmark of include using a path that requires include_path lookup versus a relative path that does not. Tested over 100000 iterations each

Results

include("include.php"):   8.3664200305939s
include("./include.php"): 8.3511519432068s

(8.3664200305939 - 8.3511519432068) / 100000 = 0.000000152680874s

Unless you're including hundreds or thousands of files, 0.0000001s is negligible at best.

Test code

define("MAX", 100000);

ob_start();
$i = MAX;
$_t = microtime(true);
do {
    include("include.php");
} while ( --$i );
$_t = microtime(true) - $_t;
ob_end_clean();

echo "include(\"include.php\"):  {$_t}s\n";

ob_start();
$i = MAX;
$_t = microtime(true);
do {
    include("./include.php");
} while ( --$i );
$_t = microtime(true) - $_t;
ob_end_clean();

Test was conducted on a 2.16GHz Macbook 10.5.8 with PHP Version 5.2.9 (www.entropy.ch Release 7)

Justin Johnson