include, require and the _once Versions
include and require run another PHP file at that point in the script; require stops with a fatal error if the file is missing while include only warns, and the _once versions skip files that were already loaded.
Follow file loading and compare failure behavior and duplicate inclusion.
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.2