Explain the difference between include, require, include_once, and require_once.
Last updated
All four pull another PHP file's contents into the current script; they differ in how they handle failure (require vs include) and whether they guard against loading the same file twice (the _once variants).
require vs include: failure behavior:
require: a missing file is a fatal error (E_COMPILE_ERROR) that halts the script.include: a missing file is only a warning (E_WARNING) and execution continues.
The _once variants: duplicate protection:
require_once/include_oncetrack loaded files and skip a second load of the same path.Prevents fatal "cannot redeclare" errors from re-defining functions or classes.
Rule of thumb:
Use
requirefor files the app can't run without;includefor optional ones.In modern projects, prefer
Composerautoloading over manualrequire_oncefor classes.
- https://pear.php.net/manual/en/standards.including.php
- https://www.php.net/manual/en/function.include-once.php
- https://dev.to/xxzeroxx/php-autoloaders-13ka
- https://stackoverflow.com/questions/2418473/difference-between-require-include-require-once-and-include-once
- https://stackoverflow.com/questions/11714358/when-should-i-use-include-require-and-require-once-in-my-examples
- https://dev.to/aminesaissihassani/difference-between-include-require-includeonce-and-requireonce-in-php-48ok
- https://www.geeksforgeeks.org/php/php-include_once-require_once/
- https://www.freecodecamp.org/news/the-php-handbook/