/compare/php/include-vs-require
PHP include vs require vs require_once: what is the difference?
- tool
- PHP
- compares
- include vs require
include and require both load and run another PHP file; they differ only when the file cannot be loaded. include emits a warning and the script continues, while require stops with a fatal error. The _once variants (include_once, require_once) do the same but skip the file if it was already loaded, which avoids "Cannot redeclare function" errors. Use require_once for files the program cannot run without (configuration, function libraries), include for optional parts such as templates, and Composer's autoloader for classes.
Differences
| Statement | File missing | Already loaded |
|---|---|---|
| include | Warning, execution continues, returns false | Loaded and run again |
| include_once | Warning, execution continues, returns false | Skipped, returns true |
| require | Fatal error, script stops | Loaded and run again |
| require_once | Fatal error, script stops | Skipped, returns true |
Example
<?php
require_once __DIR__ . '/config.php'; // must exist: stop if it is missing
require_once __DIR__ . '/vendor/autoload.php';
$settings = include __DIR__ . '/settings.local.php'; // a file can return a value
if ($settings === false) {
$settings = []; // optional file: continue with defaults
}
include __DIR__ . '/templates/footer.php'; // optional part of the pageWhen the file is missing, include reports Warning: include(settings.local.php): Failed to open stream: No such file or directory and goes on; require reports the same warning followed by a fatal error, Failed opening required ..., and stops.
Notes
- They are language constructs, not functions:
require 'file.php';andrequire('file.php');are the same. - A bare file name (
'lib.php') is searched ininclude_path, then in the calling script's directory and the current working directory; a path starting with./or../is relative to the current working directory only. Use__DIR__ . '/file.php'to make paths independent of where the script is started. - For classes, rely on autoloading (
spl_autoload_register, or Composer'svendor/autoload.php) instead of onerequire_onceper class.