PHP include_once() and require_once() Function
require_once()
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, the calling script is going to ignore further inclusions.
If abc.php is a PHP script calling xyz.php with require_once() statement and does not find xyz.php, abc.php stops execute causing a fatal error.
Syntax:
1 |
require_once('file name with path'); |
Example:
1 2 3 |
<?php echo "Welcome to PHPGurukul Programming Blog"; ?> |
The above file name is file1.php
The above file file1.php, is included twice with require_once() statement in the following file file2.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.
1 2 3 4 |
<?php require_once('file1.php'); require_once('file2.php'); ?> |
Output will be :
Welcome to PHPGurukul Programming Blog
If a calling script does not find a called script with the require_once statement, it halts the execution of the calling script.
include_once()
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:
1 2 3 |
<?php include_once('File name with path'); ?> |
The above file is file1.php
The above file file1.php is included twice with include_once() statement in the following file file2.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.
Example:
1 2 3 4 |
<?php include_once('file1.php'); include_once('file2.php'); ?> |
Output will be :
Welcome to PHPGurukul Programming Blog
If a calling script does not find a called script with the include_once statement, it halts the execution of the calling script.