QA
Beginner LevelPHP 8+

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
<?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';
💡Using __DIR__ to resolve absolute file paths for reliable file imports.
🎯 Interview Key Takeaway

Always prefix file inclusions with __DIR__ to guarantee absolute path resolution independent of the current working directory.

#__DIR__#Inclusion#Paths#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?