PHP Include / Require
PHP has four ways to bring code from another file into the current one: include, require, include_once, require_once. The difference comes down to "warning vs error" and "load once vs every time".
The matrix
| Statement | Missing file | Already loaded |
|---|---|---|
include 'x.php' | Warning, continues. | Loads again. |
include_once 'x.php' | Warning, continues. | Skips. |
require 'x.php' | Fatal error. | Loads again. |
require_once 'x.php' | Fatal error. | Skips. |
Use __DIR__ for paths
Relative paths depend on the script that started PHP — fragile. Always pin paths to the file you're in:
PHP
require __DIR__ . '/lib/config.php';
What gets included
The included file runs in the current scope. Variables defined inside it become available, functions and classes get registered globally. Most teams keep included files free of side effects — just declarations.
Modern alternative: Composer autoload
For class files, don't write require at all. Composer generates an autoloader that finds classes by name:
PHP
require __DIR__ . '/vendor/autoload.php'; use App\Billing\Invoice; $inv = new Invoice(); // file auto-loaded by Composer
When to use which
require— the file is essential. App can't run without it.require_once— library files (functions, classes) you don't want to load twice.include— optional templates or fragments; missing is OK.include_once— optional templates you don't want duplicated.
Tip: A project should have
require __DIR__ . '/vendor/autoload.php'; at the entry point — and not much else by way of require. Let the autoloader do the work.Example
Example
<?php // header.php: <h1>My site</h1> // include 'header.php'; // warns if missing // require 'header.php'; // errors if missing // include_once / require_once for libraries. echo 'use require for code you can\'t run without';Try it Yourself »
Exercise
Load a library once; fatal error if missing.
__DIR__ . '/lib/config.php';
Snake_case; 12 chars.
Discussion
Loading…