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



PHP: Tips of the Day

PHP: How to fix error with xml2-config not found when installing PHP from sources?

All you need to do instal install package libxml2-dev for example:

sudo apt-get install libxml2-dev

On CentOS/RHEL:

sudo yum install libxml2-devel

Ref : https://bit.ly/34hOrfG