PHP Include & PHP include_once


The require_once() line may include a PHP file in another when the called file has to be included several times. If the file has already been formed, the invoking script will disregard any additional inclusions.

If a.php is a PHP script that uses the require_once() command to call b.php and fails to find b.php, a.php will terminate, resulting in a fatal error.

Syntax:

require_once('name of the calling file with path');

Example:

<?php echo "today is:".date("Y-m-d"); ?>

output:

today is:2021-12-12

The preceding example, x.php, is included twice in the next file, y.php, using the require once() line. However, the result shows that the second occurrence of inclusion is disregarded, as the require once() line ignores any subsequent inclusions.

<?php require_once('x.php'); require_once('x.php'); ?>

If the require once declaration in a calling script fails to find a called script, the calling script's execution is interrupted.

include once() is a PHP function for just including a file once.

When a PHP file must be included several times, the include once() command may be used to include it in another. The calling script will ignore any subsequent inclusions if the file has already been included.

If a.php is a PHP script that uses the include once() statement to invoke b.php and the include once() statement fails to find b.php, a.php executes with a warning, omitting the code contained in b.php.

Syntax:

include_once('name of the called file with path');

Example:

<?php echo "today is:".date("Y-m-d"); ?>

The preceding example, x.php, is included twice in the next file, y.php, using the include once() command. However, the result shows that the second occurrence of inclusion is disregarded, as the include once() command ignores any subsequent such inclusions.

<?php include_once('x.php'); include_once('x.php'); ?>