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

How to use __dir__ in PHP?

PHPz
Release: 2023-08-31 22:26:02
forward
1798 people have browsed it

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
Copy after login

If we execute the code -

include "master/worker_1.php";
Copy after login

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";
Copy after login

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

<?php
include __DIR__ . "/worker_2.php";
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template