include
vs. require
: Key Differences
The two commands serve similar purposes, but they differ significantly in how they handle errors.
- The
include
statement issues a warning and continues script execution when an error occurs. - The
require
statement, however, stops the script immediately if an error happens.
This article explains the differences between include
and require
and guides you on how to choose the appropriate command for your needs.
include
vs. require
Comparison
While both include
and require
are used in PHP to include one file within another, they have a key difference:
include
generates a warning if the included file is missing but allows the script to continue running, whereas require
causes a fatal error and stops the script immediately if the file is not found.
Comparison Aspect | include |
require |
---|---|---|
Functionality | Includes a file using the include statement. |
Includes a file using the require statement. |
Usage Example | include 'filepath.php' |
require 'filepath.php' |
Error Handling | Issues a warning and continues script execution. | Triggers a fatal error and halts the script immediately. |
Duplicate Inclusion | Duplicates are allowed. | Duplicates are allowed. |
There are also modified versions of these commands called include_once
and require_once
.
As their names suggest, these commands check whether the file has already been included, and if so, they prevent including it again. This is useful to avoid errors or unintended behavior caused by redefining functions or variables when including the same file multiple times. However, compared to include
and require
, they execute slightly slower.
Comparison Aspect | include_once |
require_once |
---|---|---|
Functionality | Includes a file using the include_once statement. |
Includes a file using the require_once statement. |
Usage Example | include_once 'filepath.php' |
require_once 'filepath.php' |
Error Handling | Issues a warning and continues script execution. | Triggers a fatal error and halts the script immediately. |
Duplicate Inclusion | Duplicates are prevented. | Duplicates are prevented. |
How to Choose Between include
and require
Both include
and require
are statements used to incorporate files into your PHP script. Which one to use depends on your specific situation and requirements. Below are guidelines to help you make the right choice.
- Whether the file is mandatory
- Whether the file is optional
- Whether duplicate inclusion is allowed
- Error handling requirements
Whether the File Is Mandatory
포함하려는 파일이 반드시 필요한 경우, 스크립트 실행에 필수적인 부분이라면 require
를 선택하세요. require
는 포함되는 파일이 없을 경우에 오류를 발생시키고 스크립트를 중단시킵니다. 필수 파일이 없으면 스크립트가 올바르게 동작할 수 없는 경우에 유용합니다.
Example scenario — including database connection information in a web application.
// database.php
// Database connection details
$host = 'localhost';
$username = 'myusername';
$password = 'mypassword';
// Other database settings
// Establish database connection
$db = new PDO("mysql:host=$host;dbname=mydatabase", $username, $password);
// main.php
// Database connection info is mandatory
require 'database.php';
// Execute remaining code
// Perform database-related operations
In this example, database.php
contains critical database connection details needed by main.php
. Without this file, main.php
cannot function correctly.
Therefore, the require
statement is used to mandatorily include database.php
. This means that if the file is missing, a fatal error occurs, and the script halts immediately. This approach ensures the presence of essential files and guarantees the script runs only when required resources are available.
Whether the File Is Optional
If the file you want to include is not critical and does not affect the script’s core functionality, use include
. The include
statement will issue a warning if the file is missing but will continue running the script. This is useful for files that provide optional features.
Example scenario — including a logging file in a web application.
// logging.php
// Function to write logs
function writeLog($message) {
// Logging implementation
// ...
}
// main.php
// Optionally include logging file
include 'logging.php';
// Continue with the rest of the code
// Write logs when needed
writeLog('Event occurred');
Here, logging.php
contains functions to support logging, which is an optional feature. Including it with include
allows the script to run normally even if the logging file is missing, providing flexibility without disrupting core functionality.
Whether Duplicate Inclusion Is Allowed
Choose between include
and require
based on whether you need to include the same file multiple times. If duplication is required, use include
. If you want to prevent duplicate inclusions, use include_once
or require_once
.
Example scenario — including a module file multiple times on a web page.
// module.php
// Output module content
echo 'This is a module.';
// ...
// main.php
// Duplicate inclusion of a module file
include 'module.php';
include 'module.php';
// Output page content
echo '<main>';
// ...
echo '</main>';
In this case, module.php
is a module that might need to be included multiple times. Using include
allows multiple inclusions of the same file as needed. If preventing duplication is necessary, switch to include_once
or require_once
.
Error Handling Requirements
The choice between include
and require
also depends on how you want your script to handle errors. include
will emit a warning on failure but continue executing, whereas require
will cause a fatal error and stop execution immediately. Use require
when you need to stop the script on error.
Example scenario — including a configuration file in a web application.
// config.php
// Configuration settings
$database_host = 'localhost';
$database_username = 'myusername';
$database_password = 'mypassword';
// ...
// main.php
// Mandatory inclusion of configuration file
require 'config.php';
// Continue with the rest of the code
// Use configuration settings
$connection = new DatabaseConnection($database_host, $database_username, $database_password);
// ...
Here, config.php
contains essential configuration data. The script must halt if this file is missing or has errors.
Thus, require
is used to ensure mandatory inclusion of config.php
. This way, the script fails fast on missing or faulty configuration, safeguarding the application’s stability.
This section outlines how to select the appropriate inclusion statement based on the importance of the file, optionality, duplication needs, and error handling policies. Proper use of include
, require
, and their _once
variants is essential for robust and maintainable PHP applications.
Understanding the Importance of include
and require
Understanding the differences between include
and require
offers several advantages for PHP developers:
- Flexible Code Structure:
Knowing when to use
include
andrequire
allows you to modularize your code and break it into reusable components. You can include necessary files at the appropriate time, making your code more adaptable and maintainable. - Handling Required Files:
The
require
statement is useful for including files that are essential for the application to function. If the file is missing, it triggers a fatal error and stops the script, ensuring that critical dependencies are not silently ignored. - Handling Optional Files:
The
include
statement is ideal for optional files. If the file is not found, a warning is issued, but the script continues to run. This makes it useful for features that enhance functionality but are not required for basic execution. - Preventing Duplicate Inclusions:
You can use
include_once
andrequire_once
to prevent a file from being included multiple times. This helps maintain consistency and avoids redefinition errors. - Controlling Error Behavior:
Since
require
halts the script when an error occurs, it provides better control over how your application handles missing or broken dependencies. It ensures that critical issues are surfaced immediately.
These benefits help PHP developers create well-structured and flexible code, properly manage required and optional files, and control duplicate inclusion and error handling. By leveraging these tools effectively, you can build more reliable and maintainable PHP applications.
Summary
Understanding the differences between include
, require
, include_once
, and require_once
is essential for writing modular, maintainable PHP code. Use require
when the file is critical to the application’s functionality, and include
when the file is optional. To prevent duplicate inclusions, rely on include_once
or require_once
. Choosing the right inclusion method improves code clarity, ensures proper error handling, and helps maintain a reliable execution flow.