PHP's __DIR__ function

PHP's DIR function

Its function can be explained in one sentence here: Take out the physical path of the current script execution.

Below, let's talk about an example of using it:

There is a directory temp with a.php and subdirectories temp1 in it, and b.php and c.php in the temp1 directory.

The path is shown as follows:

temp\a.php

\ temp1

--> b.php
   --> c.php
If you need to import the b.php file in a.php, you would write:

a.php

<?php require_once 'temp1/b.php'; //... Code goes here ... ?>

c.php is introduced in b.php:

b.php

<?php require_once 'c.php'; // ... Code goes here ... ?>

At this time there is a problem!
a.php introduces b.php, but b.php introduces c.php. Here the system will directly look for c.php in the same directory as a.php! But currently this directory only has a.php file, so some unexpected things will happen in some cases.

Sometimes the code in c.php will be abnormal, or if the current directory also has c.php, c.php in two different directories will be used at the same time, etc.

To solve this problem, PHP introduced a constant variable called DIR . This will get the path of the current directory, which ensures that the file you want to import comes from that path.

Change the require_once'c.php' of b.php to require_once DIR .'/c.php' can solve the problem mentioned before:

<?php require_once __DIR .'/c.php'; // ... Code goes here ... ?>

Yes, that's it, isn't it simple?

Guess you like

Origin blog.csdn.net/weixin_45557228/article/details/109598287