PHP require Statement

PHPServer Side ProgrammingProgramming

Introduction

Effect of require statement is similar to include statement in PHP. However, there is one main difference. If the parser fails to find required file, it produces a fatal error thereby termination of current script. The include statement on the other hand emits a warning in case of failure to find file and execution of current script continues.

PHP parser tries to locate the file in current folder by default and further in directories mentioned in include_path setting of php.ini, as in case of include statement. If file asked for is not available in current folder as well as include_path folders, PHP parser emits E_COMPILE_ERRORand execution of calling module is halted.

Other behaviour of require statement is similar to include statement .

require Example

In following example main php script includes test.php

Example

 Live Demo

<?php
echo "inside main script\n";
$var1=100;
echo "now calling test.php script\n";
require "test.php";
echo "returns from test.php";
?>
//test.php
<?php
$var2=200;
//accessing $var1 from main script
echo $var1+$var2 . "\n";
?>

Output

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

inside main script<br />now calling test.php script<br /><br />300<br />returns from test.php

Error for failed require

In following example,attempt to include nonexisting file results in warning

Example

 Live Demo

<?php
echo "inside main script\n";
$var1=100;
echo "now calling nosuchfile.php script\n";
require "nosuchfile.php";
echo "returns from nosuchfile.php";
?>

Output

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

inside main script
now calling nosuchfile.php script
PHP Fatal error: require(): Failed opening required 'nosuchfile.php' (include_path='C:\xampp\php\PEAR') in line 5
Fatal error: require(): Failed
raja
Published on 18-Sep-2020 13:22:25
Advertisements