← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 19 of 24

PHP Include & Require

What Do Include and Require Do?

include and require both pull the contents of another PHP file into the current script at the point they're called, letting you split code across files instead of writing one giant script. This is the classic mechanism PHP used for modularity long before Composer autoloading existed.

Example: What Do Include and Require Do?

php
<?php
file_put_contents("helper.php", "<?php function greet() { echo 'Hello!'; }");
include "helper.php";
greet();
?>

include vs require

The only real difference is what happens when the target file is missing: include emits a warning and the script keeps running, while require raises a fatal error and execution stops immediately. Use require for files the application genuinely cannot function without, like a core config file.

Example: include vs require

php
<?php
$result = @include "missing_file.php";
echo $result === false ? "include: warning only, script continues" : "included";
?>

The _once Variants

include_once and require_once check whether the file has already been included anywhere in the current request and skip it silently if so, which prevents the "cannot redeclare function/class" fatal errors that happen when the same file gets pulled in twice through different code paths.

Example: The _once Variants

php
<?php
file_put_contents("helper.php", "<?php function greet() { echo 'Hello!'; }");
require_once "helper.php";
require_once "helper.php"; // safely skipped the second time
greet();
?>

Sharing Variable Scope

An included file runs in the exact variable scope of the line that included it — if you include a file from inside a function, that file can only see the function's local variables, not the global scope, unless you explicitly pass data in.

Example: Sharing Variable Scope

php
<?php
file_put_contents("show.php", "<?php echo \$localVar;");
function useInclude() {
    $localVar = "visible inside function";
    include "show.php";
}
useInclude();
?>

Include/Require vs Autoloading

For simple scripts, include/require are straightforward and explicit. For class-heavy applications, Composer's PSR-4 autoloading (covered elsewhere) replaces manual includes entirely by loading class files automatically the first time a class name is referenced.

Example: Include/Require vs Autoloading

php
<?php
// require 'User.php'; require 'Product.php'; ... (manual)
// vs Composer's PSR-4 autoloading (automatic, class-based)
echo "Manual includes work but don't scale like autoloading does";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.