Comparison of include and require statements in PHP
Feature | include | require |
Purpose | call specified file | call specified file |
Error Handling | Generates a warning if the file cannot be included. | Generates a fatal error if the file cannot be included. |
Effect on Script | Continues script execution even if inclusion fails. | Halts script execution if inclusion fails. |
Syntax | include 'filename'; | require 'filename'; |
Here's a brief explanation of each feature:
- Purpose: Both include and require serve the same purpose, which is to include and evaluate the contents of the specified file within the current PHP script.
- Error Handling: The main difference lies in error handling. If the included file cannot be found or accessed, include generates a warning message, but the script continues execution. In contrast, require generates a fatal error and stops script execution immediately if the file cannot be included.
- Effect on Script: Due to the difference in error handling, the choice between include and require depends on how critical the included file is for the script's functionality. If the file is not essential, you may use include to allow the script to continue executing. However, if the file is crucial, require ensures that script execution halts to prevent further issues.
- Syntax: Both statements use similar syntax, with the keyword followed by the filename enclosed in single or double quotes.
Exampe:
<?php
// Using include
echo "Using include:\n";
include 'nonexistent_file.php'; // This will generate a warning but script execution will continue
echo "This line is still executed\n";
// Using require
echo "\nUsing require:\n";
require 'nonexistent_file.php'; // This will generate a fatal error and halt script execution
echo "This line will not be executed\n";
?>
Using include:
Warning: include(nonexistent_file.php): failed to open stream: No such file or directory in your_script.php
This line is still executed
Using require:
Fatal error: require(): Failed opening required 'nonexistent_file.php' (include_path='your_include_path') in your_script.php on line 6