๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

Include and Require

File inclusion loads one PHP file inside another file. The loaded file shares its functions and variables with the file that loads it.

Include loads the helpers file

The helpers file holds a greet function and a $siteName variable. One include line makes both ready to use.

<?php
include "helpers.php";
echo greet("Ana") . "\n";
echo $siteName . "\n";

Include once loads a file one time

The second include_once line is skipped because the file is already loaded. A plain include would declare greet a second time and fail, so the two greetings print with no error.

<?php
include_once "helpers.php";
include_once "helpers.php";
echo greet("Ana") . "\n";
echo greet("Ben") . "\n";

Require stops on a missing file

The file missing.php does not exist. Require prints a warning and then a fatal error, and the last echo line never runs.

<?php
require "missing.php";
echo "This line never prints\n";

Example

<?php
include "helpers.php";
echo "Welcome to " . $siteName . "\n";
echo greet("Hana") . "\n";
echo "Your table is ready\n";

Key points

  • include loads a file at the point where the statement sits.
  • require loads a file in the same way as include.
  • A missing file gives a warning with include and the program keeps running.
  • A missing file gives a fatal error with require and the program stops.
  • The once forms include_once and require_once skip a file that was already loaded.

In this example, include loads the helpers file first. The welcome line uses $siteName from that file. The greeting uses the greet function from that file. A short closing line ends the card.

Note

A loaded file runs as if its lines were written in the file that loads it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A program loads a missing file with require. What happens next?