[Previous] [Contents] [Next]

Reusing Functions with Include and Require Files

To use functions across many PHP scripts, PHP supports the include statement and the require directive.

If you decide you wish to reuse the bold( ) function from Example 2-6 in more than one script, you can store it in an include file. For example, you can create a file called functions.inc and put the bold( ) function in the file:

<?php
function bold($string)
{
  echo "<b>" . $string . "</b>\n";
}
?>

Any PHP code in an include file must be surrounded by the PHP start and end script tags. The PHP script engine treats the contents of include files as HTML unless script tags are used.

In a script, you can then use the include statement to provide access to the function bold( ):

<html>
<head>
  <title>Simple Function Call</title>
</head>
<body bgcolor="#ffffff">
<?
include "functions.inc";
// First example function call (with a static string)
echo "this is not bold\n";
bold("this is bold");
echo "this is again not bold\n";
// Second example function call (with a variable)
$myString = "this is bold";
bold($myString);
?>
</body></html>

The script works as before, but the function bold( ) can now be reused across several scripts by including functions.inc. We use include files throughout Chapter 4 through Chapter 13.

Be careful when using the include statement. Including the same file twice or declaring a function in the script that is already in an include file causes PHP to complain about the function being redefined.

The include statement is treated in the same way as other statements. For example, you can conditionally include different files using the following code fragment:

if ($netscape == true)
{
  include "netscape.inc";
}
else
{
  include "other.inc";
}

The file is included only if the include statement is executed in the script. The braces used in this example are necessary: if they are omitted, the example doesn't behave as expected.

If a file must always be included, the require directive should be used instead of include. The require directive is processed before the script is executed, and the contents of the required file are always inserted in the script. This is useful for creating reusable HTML. For example, if you want to add the same header or footer to every page on a site-regardless of errors or other problems-require makes this easy and simple to maintain.

Consider the following HTML fragment:

<hr><br>(c) 2001 Alexa E. Williams and David Lane

If you want this fragment at the base of every page, the fragment can be stored in a file footer.inc and the directive added to the bottom of every script you develop:

require "footer.inc";

The benefit is that if you want to update the HTML footer, you need to do so in only one file.

[Previous] [Contents] [Next]