Begin Web Programming with PHP & MySQL

Advertisements



PHP include and require

The PHP include and require statements help in taking all the code which exists in the specific PHP file/doc and importing it to another file. With include and require, we can use it as a function or a statement in php. Because include() and require() are special language constructs, parentheses are not necessary around its argument.

The difference between include and require arises when the file being included cannot be found: include will emit a warning (E_WARNING) and the script will continue, whereas require will emit a fatal error (E_COMPILE_ERROR) and halt the script. If the inclusion of a file is critical to the rest of the program running correctly, then we need to use require.

Syntax:
include 'filename'; // we can use include('filename');
require 'filename'; // we can use require('filename');

1. Let us create a file named 'functions.php' and add the following code:

<?php
function table()
{
$i = 1;
while($i <= 5)
{
echo $i." x 10 = ".$i*10;
$i++;
echo '<br>';
}
}
?>

2. Create footer.php with the following code:
<h6>Thank you for visiting</h6>
3. Create index.php with the following code
<html>
<body>
<h2>Addition Table</h2>
<?php
require 'functions.php';
table(); // call function in 'functions.php'
?>
<?php
include 'footer.php';
?>
</body>
</html>
Output from index.php

Addition Table

1 x 10 = 10
2 x 10 = 20
3 x 10 = 30
4 x 10 = 40
5 x 10 = 50
Thank you for visiting