include, require and the _once Versions
Every Pageturn page needs the same header, footer and price() function. Copying them into each file means fixing every copy later. PHP lets one file pull in another, so shared pieces live in one place.
The rule
require stops if the file is missing; include warns and carries on.
<?php
require __DIR__ . '/functions.php'; // price(), lineTotal() ...
include __DIR__ . '/header.php'; // the page banner
echo "<h1>Dune</h1>";
echo price(9.99);
include __DIR__ . '/footer.php';PHP runs the named file right there, as if its code were pasted in at that spot, sharing the variables in scope.
The four statements differ on two questions:
| Missing file | Already loaded earlier | |
|---|---|---|
require |
fatal error, script stops | loads it again |
include |
warning, script continues | loads it again |
require_once |
fatal error, script stops | skipped |
include_once |
warning, script continues | skipped |
Which failure do you want? If the page cannot work without the file (functions, configuration), use require: stopping loudly beats running half-broken. If the page can survive without it, such as an optional banner, include is fine.
Why _once? Loading functions.php twice would declare price() twice, and PHP refuses to redeclare a function: fatal error. require_once remembers which files it has already loaded and skips repeats, so several parts of the code can safely ask for the same file.
Paths. A bare 'functions.php' is resolved against the include path and working directory, not necessarily this file's folder. Starting from __DIR__ always points where you expect.
An included file can also return a value. That makes a neat configuration file:
<?php
// config.php
return ['vat' => 0.20, 'currency' => 'GBP'];<?php
// any page that needs the settings
$config = require __DIR__ . '/config.php';
echo $config['vat']; // 0.2The shortcut
Ask two questions in order: "can the page live without this file?" No → require. "Could it be loaded twice?" Yes (it declares functions or classes) → add _once.
Can the page live without it?
No. Every page calls
price(). So it isrequire.
Drills
Answer fast — trust the rule.
A page uses include 'banner.php' and the file is missing. What happens?
Why might loading functions.php twice with plain require fail?
Which statement suits the database connection file?
What does $config = require __DIR__ . '/config.php'; store when config.php ends with return ['vat' => 0.20];?
Remember
- require stops if the file is missing; include warns and carries on.
- Shortcut: can the page live without it? could it load twice? That picks the statement.
- Trap: relative paths are fragile, so build paths from
__DIR__.
