QA
Beginner LevelPHP 8+

What is the difference between include, require, include_once, and require_once?

❓ Interview Prompt: Compare include vs require error severity (E_WARNING vs E_COMPILE_ERROR) and the role of the _once variants.

PHP provides four statements for importing external code files:

1. Error Severity:

•
'require': Used for mandatory application files (database configs, core classes). If the file is missing, PHP throws a Fatal Error ('E_COMPILE_ERROR') and immediately halts execution.
•
'include': Used for non-essential template files (sidebar, footer). If the file is missing, PHP emits a Warning ('E_WARNING') and continues executing the script.

2. The '_once' Suffix:

•
'require_once' and 'include_once': Check if the file was already imported previously during the current request. If so, PHP skips loading it again, preventing "Cannot redeclare function/class" fatal errors!

Code Implementation Example

php
<?php
// 1. Mandatory core configuration file (halts script if missing!)
require_once __DIR__ . '/config/database.php';

// 2. Class definition (prevents duplicate class declaration errors!)
require_once __DIR__ . '/models/User.php';

// 3. Optional UI component (script continues if missing)
include __DIR__ . '/views/partials/banner.php';
💡Using require_once for core dependencies and include for optional UI templates.
🎯 Interview Key Takeaway

require halts script execution on missing files with a Fatal Error; include emits a warning; _once prevents duplicate loading.

#include#require#require_once#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?