PHP __DIR__
Summary: in this tutorial, you’ll learn about how to use the PHP __DIR__ magic constant when including a PHP file.
Introduction to the PHP __DIR__ magic constant
PHP 5.3 introduced a new magic constant called __DIR__ . When you reference the __DIR__ inside a file, it returns the directory of the file. The __DIR__ doesn’t include a trailing slash e.g., / or \ except it’s a root directory.
When you use the __DIR__ inside an include, the __DIR__ returns the directory of the included file.
Technically speaking, the __DIR__ is equivalent to the dirname(__FILE__) . However, using the __DIR__ is more concise than the dirname(__FILE__) .
Simple PHP __DIR__example
Suppose you have the following directory structure:
. ├── inc │ ├── footer.php │ └── header.php └── index.php
Code language: CSS (css)
The header.php contains the code of the header part:
"en"> "UTF-8"> "viewport" content="width=device-width, initial-scale=1.0"> Code language: PHP (php)
The footer.php contains the code of the footer part. It also shows the value of the __DIR__ constant:
echo __DIR__ ?>