Specifications
This code will needlessly load both files every time the script is run, but only use one depend-
ing on the value of $variable. However, if the code had been written using two include()
statements, only one of the files would be loaded and used as in the following version:
if($variable == true)
{
include(“file1.inc”);
}
else
{
include(“file2.inc”);
}
Unlike files loaded via a require() statement, files loaded via an include() can return a
value. Therefore, we can notify other parts of the program about a success or failure in the
included file, or return an answer or result.
We might decide that we are opening files a lot and rather than retyping the same lines of code
every time, we want an include file to open them for us. Our include file might be called
“
openfile.inc” and resemble the following:
<?
@ $fp = fopen($name, $mode);
if (!$fp)
{
echo “<p><strong> Oh No! I could not open the file.</strong></p>”;
return 0;
}
else
{
return 1;
}
?>
This file will try to open the file named $name using the mode given by $mode. If it fails, it will
give an error message and return 0. If it succeeds, it will return 1 and generate no output.
We can call this file in a script as follows:
$name = “file.txt”;
$mode = “r”;
$result = include(“openfile.php”);
if( $result == 1 )
{
// do what we wanted to do with the file
// refer to $fp created in the include file
}
Using PHP
P
ART I
128
07 7842 CH05 3/6/01 3:35 PM Page 128