The difference between include(), include_once() and require_once() in php

In PHP, include(), include_once(), and require_once() are used to include external files into a PHP script. This is a fundamental feature for organizing code into separate files, which promotes modularity and reusability.

  1. include():

    • include() is used to include a file in a PHP script.
    • If the file is not found, it will produce a warning, but the script will continue to execute.
    • If the file contains a function or class definition, it can be called or instantiated after including the file.
    • include() does not stop the script execution if the file is not found or if there is an error in the included file.

 
 
include 'header.php';
 
echo "This is the main content.";
 
include 'footer.php';
 
 
 

include_once():

  • include_once() is similar to include(), but it ensures that the file is included only once. If the file has already been included earlier in the script or in another included file, it will not be included again.
  • This is useful to prevent problems caused by multiple declarations of the same function or class.

 
 
include_once 'config.php';
 
include_once 'config.php'; // This will be ignored.
 
 

require_once():

  • require_once() is similar to include_once() but has a stricter behavior. If the file cannot be included (e.g., file not found or syntax error), it will produce a fatal error and halt the script execution.
  • It is recommended to use require_once() when including files that are crucial for the functionality of your application.

 
 
require_once 'db_connection.php';
 
$conn = get_db_connection();
 
// Assuming this function is defined in db_connection.php
 

How It Works:

  1. include():

    • When include() is used, PHP reads the specified file and incorporates its code at the point where the include() statement is written.
    • If the file is not found, a warning is generated but the script continues running.
  2. include_once():

    • This works the same as include(), but it keeps track of files that have already been included using a list. If a file has already been included, it won't include it again.
  3. require_once():

    • Similar to include_once(), but it is more strict. If a file cannot be included, a fatal error is generated, and the script stops executing.

Choosing between them:

  • Use include() when the file you're including is not crucial for the script to run.
  • Use include_once() when you want to make sure a file is included only once.
  • Use require_once() when the file is critical for the script, and you want to ensure it's included without any errors.

Remember to use these functions judiciously based on the requirements of your application to maintain code integrity and prevent errors.