__DIR__ dùng để lấy thư mục làm việc hiện tại của code. Được giới thiệu từ PHP 5.3. Tương tự dirname(__FILE__). Thường dùng để include file khác trong file đã include.
Xét cấu trúc thư mục:
Thư mục "master" có 2 file 'worker_1', 'worker_2'. Master là subfolder của project chính.
Project cũng chứa index.php.
Xét 2 file trong thư mục 'inc', subfolder của project, nơi index.php nằm:
project_directory ├── master │ ├── worker_1.php │ └── worker_2.php └── index.php
Nếu chạy code:
include "master/worker_1.php";
từ index.php, chạy thành công.
Nhưng để chạy worker_1.php include worker_2.php, cần include tương đối đến index.php:
include "master/worker_2.php";
Dùng __DIR__ giải quyết. Từ worker_1.php chạy:
<?php include __DIR__ . "/worker_2.php";