Why is it necessary to use dirname(__FILE__) in php

Question:

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?

Answer:

http://php.net/manual/ru/function.include.php

Files are included based on the path of the specified file, or if no path is specified, the path specified in the include_path directive is used . If the file is not found in include_path , include will 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:

  1. Avoid surprises caused by interference with the include_path directive.
  2. 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 dirname(__FILE__) __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.

Scroll to Top