HomePHPWhat are the differences between include, require, include_once, and require_once?

What are the differences between include, require, include_once, and require_once?

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:

FunctionBehaviorError HandlingRepeated Inclusion
includeIncludes 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.
requireIncludes 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_onceIncludes 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_onceIncludes 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:

  1. Use require when the file is essential for your application. For example, configuration files or database connections.
  2. Use include when the file is optional, like a template file.
  3. Use _once variants 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

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *