Composing Files with include & require

Composing Files with include & require in PHP: --- A factory that builds washing machines does not fabricate every screw, motor, and control panel afresh at…


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.

StatementIf the file is missingIf already loadedYields a return value
includeWarning, script continuesRuns the file againYes, on every run
requireFatal error, script stopsRuns the file againYes, on every run
include_onceWarning, script continuesSkips, does not re-runYes on first run, then true
require_onceFatal error, script stopsSkips, does not re-runYes 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

  1. Using include for a file the program cannot run without. If a missing file would leave the script broken, include merely warns and lets it stumble on to a confusing later error. Use require for anything load-bearing -- configuration, class definitions, bootstrap code -- so a missing file stops the program at the real cause.
  1. Writing include paths relative to the current directory. A bare require 'config.php'; or require '../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.
  1. Forgetting _once on 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 with require_once so a second inclusion is safely skipped.
  1. Expecting a return value from a _once call that already ran. On its second and later calls, require_once skips the file and evaluates to true, not the array the file returns. Capture a returning config file's value with a plain require, or load it once at startup and pass the result around.
  1. Assuming array_merge merges nested arrays. It merges only the top level; a nested array in the second argument replaces the first's entirely. For layered configuration use array_replace_recursive or a deep merge, or you will silently lose nested defaults.
  1. Leaving variables leaking between the file and its caller. An included file shares the caller's variable scope, so a stray $i or $config in the included file can overwrite the caller's variable of the same name. Prefer files that return a value over files that assign into loose variables.
  1. Relying on include's warning being seen. In production, display of warnings is usually off, so a missing include file fails silently and the page renders with a hole in it. Either use require so the failure is fatal and logged, or check the file exists and handle its absence explicitly.
  1. Treating include as a function and writing include('file'). include and require are language constructs, not functions; the parentheses are merely grouping the expression and can mislead. Write require __DIR__ . '/file.php'; without wrapping parentheses so the intent is clear.
  1. 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 (or require_once) for anything the program depends on to function, and reserve include for 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 _once forms for files that declare functions, classes, or constants, so a repeated inclusion is skipped rather than crashing with a redeclaration error.
  • Prefer files that return a 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 require at load time; never depend on the value coming back from a _once call that may have already run.
  • Merge layered configuration with a recursive merge such as array_replace_recursive so 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 require lines for every class file.

Practice Exercises

  1. Create a config.php that returns an array of three settings, and a main.php that loads it with $config = require __DIR__ . '/config.php'; and prints each value. Then run main.php from a different working directory and confirm that, thanks to __DIR__, it still finds the config.
  1. Write a helpers.php that defines a single function, then a driver that includes it twice with plain include and observe the fatal redeclaration error. Change both to require_once and confirm the error is gone and the function is available.
  1. Reproduce the layered-config bug: build a base array with a nested db array containing host, port, and name, an override that sets only db.host, and merge them with array_merge. Confirm db.port is lost, then switch to array_replace_recursive and confirm it survives.
  1. Build a tiny page router that maps a $_GET['page'] value through an allow-list array (for example 'home' maps to home.php) and includes only the mapped file, falling back to a 404.php when the key is not in the list. Explain why this is safe where include $_GET['page'] would not be.