w3resource

PHP require_once(), include_once()

PHP require_once()

Description

require_once() statement can be used to include a php file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions.

If a.php is a php script calling b.php with require_once() statement, and does not find b.php, a.php stops executes causing a fatal error.

Syntax:

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

Example:

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

The above file is x.php

The above file x.php, is included twice with require_once() statement in the following file y.php. But from the output you will get that the second instance of inclusion is ignored,  since require_once() statement ignores all the similar inclusions after the first one.

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

View this example in the browser

If a calling script does not find a called script with the require_once statement, it halts the execution of the calling script.

PHP include_once()

Description

The include_once() statement can be used to include a php file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions.

If a.php is a php script calling b.php with include_once() statement, and does not find b.php, a.php executes with a warning, excluding the part of the code written within b.php.

Syntax:

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

Example:

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

The above file is x.php

The above file x.php, is included twice with include_once() statement in the following file y.php. But from the output you will get that the second instance of inclusion is ignored,  since include_once() statement ignores all the similar inclusions after the first one.

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

View the example in the browser

If a calling script does not find a called script with the include_once statement, it halts the execution of the calling script.

Previous: include and require
Next: PHP User Define Function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php/statement/require_once.php