Why should you always use the __DIR__ magic constant when including relative files in PHP?
❓ Interview Prompt: Explain relative file inclusion pitfalls, current working directory dependencies, and __DIR__ absolute path resolution.
Using relative paths like 'require "config.php";' or 'require "../bootstrap.php";' relies on the Current Working Directory (CWD) of the master executing script (e.g. 'public/index.php').
The Problem:
If a nested script or CLI command is executed from a different working directory, relative path includes fail with "Failed opening required file" errors!
The Solution - '__DIR__':
The '__DIR__' magic constant always evaluates to the absolute filesystem directory of the file in which it is written. Combining '__DIR__' with relative paths ensures file imports resolve consistently regardless of where the script was invoked.
Code Implementation Example
<?php
// ❌ Fragile relative import: Fails if working directory changes!
// require '../../config/database.php';
// ✅ Robust absolute import using __DIR__ magic constant: Always succeeds!
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/src/Services/PaymentService.php';Always prefix file inclusions with __DIR__ to guarantee absolute path resolution independent of the current working directory.