Home > Article > Backend Development > PHP gets the absolute path dirname (__FILE__) and compares it with __DIR__
We all know that to get the absolute path of the directory where the current PHP script is located, both dirname(__FILE__) and __DIR__ can be implemented. So when to use dirname(__FILE__) and when to use __DIR__? What's the difference between them? (Recommended learning: PHP video tutorial)
dirname(__FILE__) consists of two parts, __FILE__ magic variable and dirname() function . __FILE__ is the absolute path of the current script. After passing the dirname() function, you can get the absolute path of the directory where the script is located.
For example, there is a hello.php file, and the directory where it is deployed on the server is: /home/www/website/hello.php
Then, __FILE__ The value is: /home/www/website/hello.php
dirname(__FILE__) The return value is: /home/www/website/
If we use the __DIR__ global variable in hello.php, we can directly obtain the absolute path of the directory: /home/www/website/, which has the same effect as dirname(__FILE__).
In order to achieve the same function, dirname(__FILE__) has one more layer of function calls. Therefore, __DIR__ has an advantage in efficiency over dirname(__FILE__).
__FILE__ and dirname() functions have been enabled since PHP 4.0.2.
__DIR__ variable is new in PHP5.3.0.
So, if your PHP version is greater than or equal to PHP5.3.0, it is recommended to use __DIR__. Otherwise, it is better to use dirname(__FILE__) to ensure that the program does not go wrong.
The above is the detailed content of PHP gets the absolute path dirname (__FILE__) and compares it with __DIR__. For more information, please follow other related articles on the PHP Chinese website!