The Analogy: The Assembly Line and Its Parts Store
A factory that builds washing machines does not fabricate every screw, motor, and control panel afresh at the final bench. Behind the assembly line sits a parts store, and the line pulls standardised sub-assemblies from it -- a motor unit here, a pre-wired control panel there -- and fits them into the shell moving down the belt. The whole discipline of the line is that a part made once and proven good can be drawn again and again into every machine that needs it, rather than each fitter improvising their own. Bringing a file into a PHP script with include or require is exactly this: the store issues a proven sub-assembly to the bench, and its contents become part of the machine being built.
The store distinguishes sharply between two kinds of requisition, and so does PHP. A motor is structural: without it the appliance is not a washing machine at all, so if the store cannot supply one, the only correct response is to halt that machine's build and raise the alarm. That is require -- if the file is missing, PHP stops with a fatal error, because continuing would be meaningless. A branded badge glued to the front is different: nice to have, but if the badge bin is empty the machine still works, so the line fits everything else and logs a note about the missing trim. That is include -- a missing file yields a warning and the script carries on. Choosing between them is really a judgement about whether the part is load-bearing.
Some parts carry a docket. When the store issues a calibrated sensor module, it comes with a card stating its exact rating, and the fitter reads that card to set the machine correctly. A PHP file can return a value in just this way -- most often a configuration array -- and the caller captures it with $config = require 'config.php';. Other parts bear a unique serial and must be fitted exactly once: the store clerk checks the fitted-list and refuses to issue a second identical riser, because two would foul each other. That refusal is require_once and include_once, which decline to run a file that has already been pulled in, sparing you the fatal error of declaring the same function or class twice.
The failures cluster around addressing. A well-run store gives every part a fixed aisle-and-bin address, so a requisition finds the same part no matter which bench sent it. A sloppy store tells fitters to "grab it from the bin nearest you" -- and the moment a bench is moved, the fitter grabs the wrong part or none at all. Relative include paths are the nearest-bin approach: they are resolved against the process's current working directory, which changes depending on how and from where the entry script was run, so a path that worked in testing fails in production. Anchoring every path to __DIR__, the directory of the file doing the including, is the fixed-address discipline that makes composition reliable. And fitting a unique part twice -- forgetting _once on a file that declares a function -- jams the mechanism just as surely on the line as it does in the parser.
Syntax or Core Structure
include and require both evaluate another PHP file at the point they appear, as if its text had been pasted in. The difference is only in how they treat a missing file: require raises a fatal Error and stops, while include raises a warning and continues. A file may end with a return statement, and the include/require expression then evaluates to that returned value -- the standard way to load a configuration array. Paths should be anchored to __DIR__ so they resolve the same way regardless of the current working directory.
<?php
// config.php
return [
'name' => 'Ledger',
'version' => '2.4',
'workers' => 4,
];
<?php
// index.php -- captures the value the config file returns
$config = require __DIR__ . '/config.php';
echo "name = {$config['name']}\n";
echo "version = {$config['version']}\n";
echo "workers = {$config['workers']}\n";
Because config.php ends in return, the require expression yields the array directly into $config; nothing is echoed by the config file itself. Anchoring the path to __DIR__ means index.php finds its config whether it is run from the project root, from a subdirectory, or by a web server with an unrelated working directory.
Output:
name = Ledger
version = 2.4
workers = 4
Using require rather than include here is the right call: an application with no configuration cannot run, so a missing config.php should stop the program loudly rather than let it stumble on with undefined settings.
Technical Depth: Four Statements and One Path Rule
The four forms compared
There are four composition statements, formed from two independent choices: fatal-or-warning on a missing file (require versus include), and run-every-time or run-at-most-once (the plain form versus the _once suffix). The table sets out how each behaves.
| Statement | If the file is missing | If already loaded | Yields a return value |
|---|---|---|---|
include | Warning, script continues | Runs the file again | Yes, on every run |
require | Fatal error, script stops | Runs the file again | Yes, on every run |
include_once | Warning, script continues | Skips, does not re-run | Yes on first run, then true |
require_once | Fatal error, script stops | Skips, does not re-run | Yes on first run, then true |
The right-hand column hides a subtlety worth stating plainly: a _once statement returns the file's value only the first time. On any later call the file is skipped, and the expression evaluates to the boolean true instead of the array you expected. This is why you load a returning config file with plain require (or capture the value once at startup), never with require_once inside a function that runs repeatedly.
Running once versus running every time
The plain include runs a file's code afresh each time it is reached, side effects and all. The _once variants keep a record of which absolute paths have already been loaded and quietly skip a repeat. The demonstration below uses a tiny tick.php that simply echoes a line, so the run count is visible in the output.
<?php
// tick.php
echo "tick\n";
<?php
// driver-a.php -- plain include, reached twice
include __DIR__ . '/tick.php';
include __DIR__ . '/tick.php';
Output:
tick
tick
<?php
// driver-b.php -- include_once, reached twice
include_once __DIR__ . '/tick.php';
include_once __DIR__ . '/tick.php';
Output:
tick
The plain form runs tick.php both times and prints two lines; the _once form runs it only the first time. For a file whose only job is to define a function or class, running it twice is not merely wasteful -- the second run is a fatal "cannot redeclare" error, which is precisely the accident the _once forms exist to prevent.
Real World Example: A Layered Configuration Loader
Real applications rarely have a single config file. They have a base file with sensible defaults, and per-environment files that override a few of those defaults for production, staging, or local development. The loader below reads a base array and a production override, both via require, and merges them so production's values win where they are given and the base fills in the rest.
<?php
// config/base.php
return [
'app' => 'ledger',
'debug' => false,
'cache' => 'file',
'db' => ['host' => 'localhost', 'port' => 5432, 'name' => 'ledger'],
];
<?php
// config/production.php
return [
'debug' => false,
'cache' => 'redis',
'db' => ['host' => 'db.internal', 'name' => 'ledger_prod'],
];
<?php
// load.php
$base = require __DIR__ . '/config/base.php';
$override = require __DIR__ . '/config/production.php';
$config = array_merge($base, $override);
$bool = fn(bool $b): string => $b ? 'true' : 'false';
echo "effective configuration (production)\n";
echo str_repeat('-', 36), "\n";
printf("%-7s : %s\n", 'app', $config['app']);
printf("%-7s : %s\n", 'debug', $bool($config['debug']));
printf("%-7s : %s\n", 'cache', $config['cache']);
printf("%-7s : %s\n", 'db.host', $config['db']['host']);
printf("%-7s : %s\n", 'db.port', $config['db']['port'] ?? 'unset');
printf("%-7s : %s\n", 'db.name', $config['db']['name']);
Output:
effective configuration (production)
------------------------------------
app : ledger
debug : false
cache : redis
db.host : db.internal
db.port : unset
db.name : ledger_prod
The composition works cleanly at the top level: app survives from the base because production does not mention it, while cache and db.host take production's values. Loading each file with require is the right choice, since a missing config file should stop the program rather than let it run with half its settings. Anchoring both paths to __DIR__ means load.php finds its config directory no matter what working directory the web server or the test runner happens to use.
But the output reveals a real and common design flaw: db.port is unset, even though the base file clearly set it to 5432. The cause is array_merge, which merges only the top level. When both arrays have a db key, production's db array replaces the base's db array wholesale rather than merging into it, so the base's port is silently discarded because production's db block did not repeat it. This is not a rough edge; it is a bug waiting for the day someone relies on a nested default. The fix is a recursive merge -- array_replace_recursive for this override-wins case, or a hand-written deep merge -- so that nested arrays combine key by key instead of the whole branch being overwritten. Until then, every environment file must redundantly repeat every nested key it wants to keep, which is exactly the fragile obligation that composition was meant to remove.
Common Mistakes
- Using
includefor a file the program cannot run without. If a missing file would leave the script broken,includemerely warns and lets it stumble on to a confusing later error. Userequirefor anything load-bearing -- configuration, class definitions, bootstrap code -- so a missing file stops the program at the real cause.
- Writing include paths relative to the current directory. A bare
require 'config.php';orrequire '../lib/db.php';is resolved against the process's working directory, which differs between the CLI, a web server, and a test runner. Anchor every path to__DIR__so it resolves against the including file's own location.
- Forgetting
_onceon a file that declares a function or class. Including such a file twice with the plain form is a fatal "cannot redeclare" error. Files that define functions, classes, or constants should be pulled in withrequire_onceso a second inclusion is safely skipped.
- Expecting a return value from a
_oncecall that already ran. On its second and later calls,require_onceskips the file and evaluates totrue, not the array the file returns. Capture a returning config file's value with a plainrequire, or load it once at startup and pass the result around.
- Assuming
array_mergemerges nested arrays. It merges only the top level; a nested array in the second argument replaces the first's entirely. For layered configuration usearray_replace_recursiveor a deep merge, or you will silently lose nested defaults.
- Leaving variables leaking between the file and its caller. An included file shares the caller's variable scope, so a stray
$ior$configin the included file can overwrite the caller's variable of the same name. Prefer files thatreturna value over files that assign into loose variables.
- Relying on
include's warning being seen. In production, display of warnings is usually off, so a missingincludefile fails silently and the page renders with a hole in it. Either userequireso the failure is fatal and logged, or check the file exists and handle its absence explicitly.
- Treating
includeas a function and writinginclude('file').includeandrequireare language constructs, not functions; the parentheses are merely grouping the expression and can mislead. Writerequire __DIR__ . '/file.php';without wrapping parentheses so the intent is clear.
- Including files whose paths come from user input. Building an include path from a request parameter --
include $_GET['page'] . '.php';-- is a serious local-file-inclusion vulnerability that can run arbitrary files. Map user input to a fixed allow-list of known filenames and include only those.
Best Practices
- Use
require(orrequire_once) for anything the program depends on to function, and reserveincludefor genuinely optional fragments whose absence is acceptable.
- Anchor every include path to
__DIR__so composition works identically from the CLI, a web server, and the test suite regardless of working directory.
- Use the
_onceforms for files that declare functions, classes, or constants, so a repeated inclusion is skipped rather than crashing with a redeclaration error.
- Prefer files that
returna value -- especially configuration arrays -- over files that populate loose variables, keeping the included file's effect explicit and its scope clean.
- Capture a returning file's value with a single plain
requireat load time; never depend on the value coming back from a_oncecall that may have already run.
- Merge layered configuration with a recursive merge such as
array_replace_recursiveso nested defaults survive an override that does not repeat them.
- Never build an include path from untrusted input; map any user-supplied selector to a fixed allow-list of filenames you control.
- For a project of any size, adopt an autoloader (Composer's PSR-4) so classes load on demand and you stop hand-writing
requirelines for every class file.
Practice Exercises
- Create a
config.phpthat returns an array of three settings, and amain.phpthat loads it with$config = require __DIR__ . '/config.php';and prints each value. Then runmain.phpfrom a different working directory and confirm that, thanks to__DIR__, it still finds the config.
- Write a
helpers.phpthat defines a single function, then a driver that includes it twice with plainincludeand observe the fatal redeclaration error. Change both torequire_onceand confirm the error is gone and the function is available.
- Reproduce the layered-config bug: build a base array with a nested
dbarray containinghost,port, andname, an override that sets onlydb.host, and merge them witharray_merge. Confirmdb.portis lost, then switch toarray_replace_recursiveand confirm it survives.
- Build a tiny page router that maps a
$_GET['page']value through an allow-list array (for example'home'maps tohome.php) and includes only the mapped file, falling back to a404.phpwhen the key is not in the list. Explain why this is safe whereinclude $_GET['page']would not be.