Home  >  Article  >  Backend Development  >  How to use __dir__ in PHP?

How to use __dir__ in PHP?

PHPz
PHPzforward
2023-08-31 22:25:061718browse

How to use __dir__ in PHP?

__DIR__ can be used to get the current code working directory. It was introduced starting with PHP version 5.3. It is similar to using dirname(__FILE__). Typically used to include other files that exist within an included file.

Consider the following directory structure -

A directory named "master" with two files named 'worker_1' and 'worker_2'. The master directory itself is a subfolder of the main project directory.

The project directory also contains an index.php file.

Consider there are two files in a directory called inc, which is a subfolder of our project directory, where the index.php file is located -

project_directory
├── master
│ ├── worker_1.php
│ └── worker_2.php
└── index.php

If we execute the code -

include "master/worker_1.php";

From index.php, it runs successfully.

But to run worker_1.php by including worker_2.php, a relative inclusion of the index.php file must be done as shown below -

include "master/worker_2.php";

Using __DIR__ will make it run. The following code can be executed from worker_1.php -

<?php
include __DIR__ . "/worker_2.php";

The above is the detailed content of How to use __dir__ in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete