require and include in php

PHP provides two very simple, yet very useful, statements to allow you to reuse code. Using a require() or include() statement, you can load a file into your PHP script. The file can contain anything you would normally have in a script including PHP statements, text, HTML tags, PHP functions, or PHP classes.

The statements require() and include() are almost identical. The only difference between them is that when they fail, the require() construct gives a fatal error, whereas the include() construct gives only a warning

There are two variations on require() and include(), called require_once() and include_once(), respectively. The purpose of these constructs is, as you might guess, to ensure that an included file can be included only once. This functionality becomes useful when you begin using require() and include() to include libraries of functions. Using these constructs protects you from accidentally including the same function library twice, thus redefining functions and causing an error. If you are cautious in your coding practices you are better off using require() or include() as these are faster to execute

Using require() to include code

The following code is stored in a file named reusable.php:

<?php
 echo 'Here is a very simple PHP statement.<br />';
?> 

The following code is stored in a file named main.php:

<?php
 echo 'This is the main file.<br />';
 require('reusable.php');
 echo 'The script will end now.<br />';
?>

Leave a Comment