Junior
What is the difference between the require and include functions in PHP?
sobes.tech AI
Answer from AI
Differences in error handling when including a file.
- require: When an error occurs (file not found or inaccessible), it generates a fatal error (
E_COMPILE_ERROR), and script execution stops. - include: When an error occurs, it generates a warning (
E_WARNING), but script execution continues.
| Function | Error type on failure | Continue execution |
|---|---|---|
| require | E_COMPILE_ERROR |
No |
| include | E_WARNING |
Yes |
Using require is preferable for critical files (e.g., configuration, libraries), without which the script's work is meaningless. include is suitable for optional files (e.g., templates, widgets).
There are also require_once and include_once versions, which check if the file has already been included and include it only once.
<?php
// Example of using require
// If the file non_existent_critical_file.php does not exist, the script will stop.
// require 'non_existent_critical_file.php';
// Example of using include
// If the file non_existent_optional_file.php does not exist, a warning will be issued,
// but the script will continue.
// include 'non_existent_optional_file.php';
?>