The include_once Function
The include_once
function includes the specified file in the current PHP script, but only if it has not been included before. This is especially useful when working with files containing function or class declarations to avoid redeclaration errors. The function's parameter is the path to the file to be included.
Syntax
include_once 'path/to/file.php';
Example
Include the config.php
file only once:
<?php
include_once 'config.php';
include_once 'config.php'; // This call will be ignored
?>
Example
Attempt to include a non-existent file:
<?php
include_once 'nonexistent.php'; // Will generate a warning, but will not stop script execution
echo 'Script continues...';
?>
Code execution result:
Warning: include_once(nonexistent.php): failed to open stream: No such file or directory
Script continues...
Example
Using a variable to specify the path:
<?php
$filePath = 'lib/functions.php';
include_once $filePath;
?>
See Also
-
the
include
function,
which includes a file without checking for repeated inclusion -
the
require
function,
which includes a file with script termination on error -
the
require_once
function,
which works like include_once, but stops the script on error