In PHP, include, require, include_once, and require_once are all used to include and evaluate files, but they behave differently in terms of error handling and repeated inclusions. Here’s a detailed comparison:
| Function | Behavior | Error Handling | Repeated Inclusion |
|---|---|---|---|
include | Includes and evaluates the specified file. | If the file is not found, a warning is generated, but the script continues execution. | Can include the same file multiple times, potentially redefining functions, classes, or variables. |
require | Includes and evaluates the specified file. | If the file is not found, a fatal error occurs, and the script stops execution. | Can include the same file multiple times, same as include. |
include_once | Includes the file only once even if called multiple times. | Same as include (warning if file not found, script continues). | Prevents multiple inclusions, avoiding function/class redeclaration errors. |
require_once | Includes the file only once, like include_once. | Same as require (fatal error if file not found, script stops). | Prevents multiple inclusions. |
Key Points to Remember:
- Use
requirewhen the file is essential for your application. For example, configuration files or database connections. - Use
includewhen the file is optional, like a template file. - Use
_oncevariants to avoid redeclaration errors when a file might be included multiple times.
Example:
// include
include 'header.php'; // warning if file missing, script continues
// require
require 'config.php'; // fatal error if file missing, script stops
// include_once
include_once 'functions.php'; // included only once
// require_once
require_once 'database.php'; // included only once, fatal error if missing
