File Inclusion
Tutorials

As your PHP projects grow, keeping all your code in a single file becomes impossible to manage.

PHP allows you to split your codebase into separate, organized files (like separating your classes, configuration files, or functions) and pull them into your scripts using file inclusion statements.

The primary statements used to load external files are require, require_once, include, and include_once.

The Core Standard: require vs. require_once

In professional PHP development, you should almost exclusively rely on the require family.

The require statement tells PHP that the target file is absolutely mandatory for the application to function.

If the file cannot be found or contains an error, PHP will trigger a fatal Error (Fatal Error) and halt script execution instantly.

This prevents your application from running in a broken or insecure state.

require

Pulls in the file's content immediately.

If you call require on the same file multiple times, PHP will inject it multiple times, which can cause duplicate definition conflicts.

<?php
// FILE: tools.php
function myFunction(): void
{
    echo "This is my function";
}

// FILE: main.php
require "tools.php";
echo "This code will never execute if config.php is missing!\n";

require_once (Recommended Default)

The _once suffix instructs PHP to check if the file has already been loaded during the current script runtime.

If it has, PHP intelligently skips the request to load it again.

This is essential when loading files that define structures like classes or functions, as declaring them twice results in a fatal crash.

<?php
// UserClass.php contains: class UserClass { ... }

require_once "UserClass.php";
require_once "UserClass.php"; // PHP skips this line safely. No duplicate errors!

Relegated Alternative: include and include_once

The include statement behaves similarly to require, but with one critical flaw: if the file cannot be found, PHP only issues a Warning and allows the script to continue running.

Because running a script when a dependency is completely missing introduces fragile behavior and silent bugs, include is rarely used in modern production code.

Best Practice Implementation

These file inclusion statements are language constructs rather than standard functions, meaning wrapping parentheses are completely optional.

It is standard practice among PHP developers to omit the parentheses entirely and separate the keyword from the absolute file path with a single space.

To construct this absolute path securely, always prefix your files with the magic constant DIR. This constant automatically evaluates to the absolute directory path of the current file writing the code, preventing folder-nesting bugs.

<?php
// Standard, clean readability (Recommended)
require_once __DIR__ . "/config/bootstrap.php";

// Functional style (Valid syntax, but discouraged)
require_once(__DIR__ . "/config/bootstrap.php");
To Top