If you include the same file twice, PHP runs it twice. For a file that declares functions or classes, that is a fatal error, because you cannot declare the same function twice.
<?php
function sayHi(): string
{
return "Hi!";
}
<?php
require "helpers.php";
require "helpers.php"; // second time: error
Fatal error: Cannot redeclare sayHi() (previously declared in /path/to/helpers.php:3) in /path/to/helpers.php on line 3
The _once versions
include_once and require_once remember which files they have already loaded, and skip a file that was loaded before.
<?php
function sayHi(): string
{
return "Hi!";
}
<?php
require_once "helpers.php";
require_once "helpers.php"; // ignored, already loaded
echo sayHi();
Hi!
When to use them
- Files that define functions, classes or constants: use
require_once. - Files that output HTML (a header or footer you want to show twice): use plain
includeorrequire.
<?php
require_once __DIR__ . "/functions.php"; // safe to repeat anywhere
include __DIR__ . "/templates/sidebar.php"; // can appear several times
How PHP knows it is the same file
PHP compares the full resolved path. So "./helpers.php" and "helpers.php" and __DIR__ . "/helpers.php" all count as one file. That is another reason to use full paths (see File Paths).
The cost
The _once check has a small cost. It is far smaller than a bug from a double load, but in modern projects you rarely write any of this by hand. Autoloading loads classes for you the first time they are used. Autoloading and Composer cover that.
Quick summary
| Statement | Missing file | Loads again if repeated |
|---|---|---|
include | Warning | Yes |
require | Fatal error | Yes |
include_once | Warning | No |
require_once | Fatal error | No |
A simple rule
require_once for code files, include for pieces of HTML, and Composer’s autoloader for classes.