PHP gets absolute path dirname(__FILE__) and __DIR__ comparison

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 is the difference between them?

Functionality and Efficiency

dirname(__FILE__) consists of two parts, the __FILE__ magic variable and the dirname() function. __FILE__ is the absolute path of the current script. After passing the dirname() function, the absolute path of the directory where the script is located can be obtained.

For example, there is a hello.php file, which is deployed in the server directory: /home/www/website/hello.php

So,

  • The value of __FILE__ is: /home/www/website/hello.php
  • dirname(__FILE__) returns: /home/www/website/

If we use the __DIR__ global variable in hello.php, we can directly get the absolute path of the directory: /home/www/website/, which is exactly the same as dirname(__FILE__).

In the case of implementing the same function, dirname(__FILE__) has one more layer of function calls. Therefore, __DIR__ has an efficiency advantage over dirname(__FILE__).

PHP version support

The __FILE__ and dirname() functions have been enabled since PHP 4.0.2.

The __DIR__ variable is newly added 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's better to use dirname(__FILE__) to make sure the program doesn't error out.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325260647&siteId=291194637