Home php Why use dirname (__ FILE__) in php

Why use dirname (__ FILE__) in php




In many projects I saw the connection of a third-party file in this form:

& lt;? php
 include (dirname (__ FILE__). '/file.php');
? & gt;

In theory, this code does the same thing:

& lt;? php
 include ('file.php');
? & gt;

So what’s the difference and why do programmers use the first option?

Answer 1, authority 100%


Files are included based on the & nbsp; path of the specified file, or if the path is not & nbsp; specified, the path specified in the directive include_path . If the file is not & nbsp; found in & nbsp; include_path , include will try to check the directory that & nbsp; contains the current include script and & nbsp; current working directory before throwing an error.

Therefore, I see two reasons for specifying an absolute path:

  1. Avoid surprises caused by the intervention of the include_path directive.
  2. Speed ​​up the work: go straight to the & nbsp; absolute path, and & nbsp; not & nbsp; iterate over directories that may be implied.

Since version 5.3, __DIR__ can be used instead of dirname (__ FILE__) . The & nbsp; answer says it might work even faster because __DIR__ is defined to & nbsp; compile time, and & nbsp; dirname (__ FILE__) means a function call and & nbsp; therefore happens at & nbsp; runtime.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions