Computer >> Computer tutorials >  >> Programming >> PHP

PHP require_once Statement


Introduction

The require_once statement in PHP is similar in functioning to that of require statement. Only difference is, if a file has been already included for processing, it will not be included again.Note that a file included with either include or require statement will also be not included again even if require_once statement is used.

Other behaviour of require_once statement is similar to require statement .

require_once Example

In following example main php script includes test.php

Example

<?php
echo "inside main script\n";
echo "now including with require_once test.php script\n";
require_once "test.php";
echo "try to include it again";
require_once "test.php";
?>
//test.php
<?php
echo "File included\n";
?>

Output

This will produce following result when main script is run from command line −

inside main script
now including with require_once test.php script
File included
try to include it again

Error for failed require_once

require_once statement too causes fatal error when trying to add nonexisting file

Example

<?php
echo "inside main script\n";
echo "now including with require_once notest.php script\n";
require_once "notest.php";
?>

Output

This will produce following result. Note that program is teerminated on error −

inside main script
now including with require_once notest.php script
PHP Fatal error: require_once(): Failed opening required 'notest.php' (include_path='C:\xampp\php\PEAR') in line 4
Fatal error: require_once(): Failed opening required 'notest.php' (include_path='C:\xampp\php\PEAR') in line 4