At root, require
, require_once
, include
, and include_once
all perform the same task of
including one file in another. However, the way they perform that task differs, and they should not be used interchangeably.
require
includes a file but generates a fatal error if an error occurs in the process.
include
also includes a file, but generates only a warning if an error occurs.
Predictably, the difference between require
and require_once
is the same as the difference between include
and include_once
- the "_once" versions ensure that the specified file is only included once.
Because including the same file multiple times could have unpredictable results, the "once" versions are preferred.
Because include_once
generates only warnings, it should be used only when the file is being included conditionally, i.e. when all
possible error conditions have been checked beforehand.
Noncompliant Code Example
include 'code.php'; //Noncompliant; not a "_once" usage and not conditional
include $user.'_history.php'; // Noncompliant
require 'more_code.php'; // Noncompliant; not a "_once" usage
Compliant Solution
require_once 'code.php';
if (is_member($user)) {
include_once $user.'_history.php';
}
require_once 'more_code.php';