Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?

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.

like image 969
datasn.io Avatar asked Feb 08 '10 08:02

datasn.io


2 Answers

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.

like image 115
Gumbo Avatar answered Oct 30 '22 13:10

Gumbo


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)

like image 31
Justin Johnson Avatar answered Oct 30 '22 12:10

Justin Johnson