288 of 410 menu

The require_once Function

The require_once function includes the specified file in the current script. If the file has already been included previously, the function will not include it again. This is especially useful for including files with classes or functions, where re-inclusion can cause errors.

Syntax

require_once 'path/to/file.php';

Example

Let's include the config.php file:

<?php require_once 'config.php'; echo $config['site_name']; ?>

Code execution result (if the $config array is defined in config.php):

'My Site'

Example

Attempting to re-include the same file:

<?php require_once 'functions.php'; require_once 'functions.php'; // This call will be ignored echo sum(2, 3); ?>

Code execution result:

5

Difference from require

Unlike require, the require_once function checks if the file has already been included and does not perform re-inclusion. This prevents errors when including the same file multiple times.

See Also

  • the include function,
    which also includes files but does not check for their re-inclusion
  • the include_once function,
    which works similarly to require_once but does not cause a fatal error if the file is missing
byenru