include and require compile another file and run it in the current scope. The file must open with <?php (anything else is output as HTML) and may return a value, otherwise the result is 1. Here config.php is <?php return ['db' => 'shop', 'tax' => 0.08]; and lib/helpers.php defines shout().
<?php
$config = require __DIR__ . '/config.php'; // the included file's return value
echo "db={$config['db']} tax={$config['tax']}\n";
var_dump(require_once __DIR__ . '/config.php'); // already included: true, not the array
set_include_path(__DIR__ . '/lib' . PATH_SEPARATOR . get_include_path());
include 'helpers.php'; // a relative name: searched on the path
echo shout('order shipped'), "\n";
var_dump(@include 'missing.php'); // two warnings (hidden by @), then false
try {
@require 'missing.php'; // PHP 8: an Error, fatal if uncaught
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}Output
db=shop tax=0.08 bool(true) ORDER SHIPPED! bool(false) Error: Failed opening required 'missing.php' (include_path='/home/dev/app/lib:.:/usr/share/php' )
On failure include warns and returns false; require stops the script, since PHP 8.0 with a catchable Error. The _once forms skip a file already loaded. A relative name is searched along include_path (Ubuntu 225 's default .:/usr/share/php), whose . is the working directory, so anchor includes with __DIR__.