Introduction
Just as the include statement, include_once also transfers and evaluates script written in one file in another, the difference in two lies in the fact that include_once prevents same file from reloading if already done. As the name indicates, a file will be included only once even if one tries to issue include instruction again.
The include_once statement is typically used to set up global variables, enable libraries or any such activity that is expected to be done in the beginning of execution of application.
Other than this, behaviour of include_once statement is similar to include statement.
include_once Example
In following example testscript.php is present in document root folder of Apache server. It inserts test.php using include_once statement
Example
<?php echo "calling include_once statement\n"; $result=include_once "test.php"; ?> //test.php <?php echo "This file is included once\n"; ?>
Output
This will produce following result in the browser if URL of testscript.php is given−
calling include_once statement
This file is included once
Warning for failed include
Warning is emitted by parser if file argument og include_once statement is not found
Example
<?php echo "inside main script<br />"; $var1=100; echo "now calling nosuchfile.php script"; include_once "nosuchfile.php"; echo "returns from nosuchfile.php"; ?>
Output
This will produce following result. Note that program doesn't teerminate on warning −
inside main script now calling nosuchfile.php script PHP Warning: include_once(nosuchfile.php): failed to open stream: No such file or directory in line 5 PHP Warning: include_once(): Failed opening 'nosuchfile.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 5 returns from nosuchfile.php
include_once called again
Next example includes test.php with include_once statement. Note that same file is not included again
Example
//main script <?php echo "inside main script<br>"; echo "now including test.php script<br>"; include_once "test.php"; echo "now including again test.php script<br>"; ?> //test.php included <?php echo "This file is included once"; ?>
Output
This will produce following result in the browser−
inside main script<br />now including test.php script<br />
This file is included once
now including again test.php script