In this chapter
We'll learn how to split a project into files with include and require, why an included file shares the variables of the line that includes it, how a file can return a value like a config array, why include_once and require_once prevent "Cannot redeclare", how PHP finds a file from a relative path — and why __DIR__ makes paths that work from the browser and the terminal alike.
The Problem in Real Life
Mia splits the 900-line file. config.php holds the settings; src/time-helpers.php, src/slots.php and src/prices.php hold the functions; public/booking.php is the page; and bin/send-reminders.php is a new script that Tom's server will run every evening from the terminal.
Three things break. The booking page always shows 5 November, whatever date the customer picks. php send-reminders.php dies with "Cannot redeclare function formatTime()" — yet the website, which uses the same files, works. And when the server runs the script on its own at 18:00, the log says "Failed to open stream: No such file or directory" for ../config.php, a file that's right there.
Same files, same code. Why does it work in the browser and fail in the terminal?
Mia
One Big File vs. Many Small Ones
Included files share your variables
An included file runs as if it were pasted in at that line. Its variables can overwrite yours.
Loaded twice
Two files that both include the same helpers make PHP declare the same functions twice.
Relative to what?
"../config.php" means "one folder up from where you are" — and in a terminal, that depends on where you typed the command.
include, require and File Paths
Splitting code into files: real projects are many small files, each with one job. PHP joins them at runtime with four statements and a few path rules. This chapter covers:
- include and require: loading another file, and what happens when it's missing.
- Include scope: which variables an included file sees and changes.
- Return values: files that hand back a value, like a config array.
- include_once and require_once: loading a file only once.
- Paths: how PHP finds a file, and
__DIR__,__FILE__and__LINE__.
include and require: require "file.php"; reads another PHP file and runs it right there, as if its code were pasted in at that line. include does the same. The difference is what happens when the file can't be loaded: include prints a warning, returns false and carries on with the next line; require stops the script with a fatal error. Code that your page needs — functions, settings — should be loaded with require: a page that runs on without its price functions is worse than a page that stops. Both are language constructs, so the brackets are optional; require "file.php"; is the usual style.
bookbay/├── config.php returns the settings├── src/│ ├── time-helpers.php formatTime()│ ├── slots.php slotsFor()│ └── prices.php calculatePrice(), formatPrice()├── public/ the document root (Act 01): only this is on the web│ └── booking.php the booking page└── bin/└── send-reminders.php run from the terminal every evening
<?php$loaded = include "missing-file.php";var_dump($loaded); // bool(false), after a warningecho "include: still running\n";require "missing-file.php";echo "require: never printed\n";// Warning: include(missing-file.php): Failed to open stream: No such file or directory// bool(false)// include: still running// Warning: require(missing-file.php): Failed to open stream: No such file or directory// Fatal error: Uncaught Error: Failed opening required 'missing-file.php'
Include scope: an included file runs in the scope of the line that includes it. Included at the top level of booking.php, its code runs in the global scope: it sees all of the page's variables, and every variable it sets becomes the page's variable too. That's the first bug. booking.php set $date from the customer's choice, then required src/slots.php — which had a line of its own, $date = "2026-11-05";, a default left over from testing. It quietly overwrote the customer's date. Included inside a function, a file's variables are local to that function instead. Functions, constants and classes it declares are always global. The rule that prevents all of this: a file in src/ should only declare things — functions, constants, later classes — and never set loose variables.
<?php// ---- src/slots.php ----$date = "2026-11-05"; // a test default, left in by mistakefunction slotsFor(string $date): array{return ["9:00", "9:30", "10:00"];}// ---- public/booking.php ----$date = $_GET["date"] ?? date("Y-m-d"); // the customer picked 2026-11-10require __DIR__ . "/../src/slots.php"; // runs slots.php right here, in the same scopeecho "Free slots on $date: ", implode(" ", slotsFor($date)), "\n";// Free slots on 2026-11-05: 9:00 9:30 10:00 — the customer's date is gone
Files that return a value: an included file can end with return and a value, and include/require give that value back. config.php can be just return ["shop" => "Tom's Barbershop", "holidayPercent" => 10];, and every script loads it with $config = require __DIR__ . "/../config.php";. The settings arrive in a variable that you name, instead of appearing as loose globals. This is exactly how Laravel's config files work. A file without return gives back 1; a failed include gives back false.
<?php// ---- config.php ----return ["shop" => "Tom's Barbershop","holidayPercent" => 10,"timezone" => "Europe/London",];// ---- bin/send-reminders.php ----$config = require __DIR__ . "/../config.php"; // the returned array, in a variable you nameecho $config["shop"], ", surcharge ", $config["holidayPercent"], "%\n";// Tom's Barbershop, surcharge 10%
include_once and require_once: require_once remembers every file it has loaded in this request, by its full path. Asking for the same file again does nothing and returns true. That's the second bug. src/slots.php and src/prices.php each started with include "time-helpers.php";. The booking page only needs slots, so it loaded the helpers once and worked. The reminder script needs slots and prices, so it loaded the helpers twice, and the second time PHP tried to declare formatTime() again — the fatal error from Act 09. The fix: load every file that declares functions with require_once. (Act 13 replaces most of these lines with autoloading, which loads files automatically when a class is first used.)
<?php// ---- src/slots.php ----include "time-helpers.php"; // declares formatTime()// ---- src/prices.php ----include "time-helpers.php"; // declares formatTime() AGAIN// ---- public/booking.php: needs only slots → works ----require __DIR__ . "/../src/slots.php";// ---- bin/send-reminders.php: needs slots AND prices → dies ----require __DIR__ . "/../src/slots.php";require __DIR__ . "/../src/prices.php";// Fatal error: Cannot redeclare function formatTime()// (previously declared in /var/www/bookbay/src/time-helpers.php:2)// ---- The fix, at the top of slots.php and prices.php ----require_once __DIR__ . "/time-helpers.php"; // loaded once per request, however often it's asked for
How PHP finds a file: a path that starts with / (or a drive letter on Windows) is absolute: PHP loads exactly that file. A path that starts with ./ or ../ is relative to the current working directory (CWD) — the folder the process is "standing in". In a terminal, that's the folder where you typed the command; on the web, it's usually the folder of the requested script. Any other path, like plain "time-helpers.php", is searched for in the folders of the include_path setting (php.ini) and then in the folder of the file that contains the include line. That's the third bug. require "../config.php"; worked when Mia tested it with cd bin and then php send-reminders.php. But the server runs php /var/www/bookbay/bin/send-reminders.php from a different folder, so "one folder up" pointed somewhere else.
$ cd /var/www/bookbay/bin$ php send-reminders.php # CWD is bin/, so ../config.php is bookbay/config.phpReminders for Tom's Barbershop$ cd /$ php /var/www/bookbay/bin/send-reminders.php # CWD is /, so ../config.php is /config.phpPHP Warning: require(../config.php): Failed to open stream: No such file or directoryPHP Fatal error: Uncaught Error: Failed opening required '../config.php' (include_path='.:/usr/share/php')
Magic constants: PHP has a few constants whose value depends on where they're written, called magic constants. __FILE__ is the full path of the file the line is in, __DIR__ is that file's folder, and __LINE__ is the line number. Unlike the CWD, they never change, whoever runs the script from wherever. So the rule for every include is: start from __DIR__. require_once __DIR__ . "/../src/prices.php"; loads the same file from the browser, from the terminal, from any folder and from the server's scheduler. The table below sums up the chapter.
| Statement | If the file is missing | If it was already loaded | Returns |
|---|---|---|---|
| include | Warning, carries on | Loads it again | The file's return value, 1, or false |
| require | Fatal error, stops | Loads it again | The file's return value or 1 |
| include_once | Warning, carries on | Does nothing | true if already loaded |
| require_once | Fatal error, stops | Does nothing | true if already loaded |
| You write | PHP looks | Safe from the terminal? |
|---|---|---|
| "/var/www/bookbay/config.php" | Exactly there | Yes, but tied to one server |
| "../config.php" or "./config.php" | Relative to the current working directory | No: depends on where you ran php |
| "time-helpers.php" | In the include_path folders, then in the including file's folder | Usually, but hard to predict |
| __DIR__ . "/../config.php" | Relative to the file that contains this line | Yes: always the same file |
<?phpecho __FILE__, "\n"; // the full path of this fileecho __DIR__, "\n"; // the folder it's inecho __LINE__, "\n"; // 5: the line numberecho getcwd(), "\n"; // the current working directory: depends on how PHP was started// In the Playground the file is main.php in /, so this prints:// main.php// /// 5// /
<?php// ---- bin/send-reminders.php ----declare(strict_types=1);$config = require __DIR__ . "/../config.php";require_once __DIR__ . "/../src/slots.php";require_once __DIR__ . "/../src/prices.php";echo "Reminders for {$config['shop']}\n";// Works from anywhere:// $ cd / && php /var/www/bookbay/bin/send-reminders.php// Reminders for Tom's Barbershop
Key Takeaway
require loads another file and runs it right there (a missing file is fatal; include only warns). An included file shares the scope of the line that includes it, so files in src/ should only declare functions and constants, and config files should return an array. require_once loads each file once per request and prevents "Cannot redeclare". Paths starting with ./ or ../ depend on the current working directory — build every path from __DIR__ instead.
Why This Matters
Every PHP project bigger than a page is split into files, and every one of them depends on these rules. The bugs they cause are some of the most confusing in PHP — "it works on my machine", "it works in the browser", "it worked yesterday" — because the code is fine; only the way it's loaded is wrong.
Three habits make them disappear: src/ files only declare things, everything is loaded with require_once, and every path starts from __DIR__. Composer and Laravel (Act 13 and the next course) automate this, but they follow exactly the same rules underneath.
The booking page shows the customer's date, the reminder script runs from any folder, and nothing is declared twice. Olivia is impressed and asks for a small extra on the admin page: "Bookings made today". Mia adds a counter — a static variable that goes up by one with every booking. Twelve people book that afternoon. The admin page says 1. That's the next chapter: what PHP does from the start of a request to its end.
