Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

to the database, and if any functions are defined, PHP will report the error of a duplicate
function.


In C, programmers avoid this situation by defining constants inside the included files, and
you can adopt a similar strategy. You can define a constant inside your module. If this
constant is already defined when the module is executed, control is immediately returned
to the calling process. A function named printBold is defined in Listing 21.1. This


function is needed in the script shown in Listing 21.2. I've purposely placed a bug in
the form of a second include. The second time the module is included, it will return
before redeclaring the function.


Listing 21.1 Preventing a Double Include


<?
/*
* Avoid double includes
/
$includedflag = 'INCLUDE'. basename(FILE);
if(defined($included_flag))
{
return(TRUE);
}
define($included_flag, TRUE);


function printBold($text)
{
print("$text");
}
?>


Listing 21.2 Attempting to Include a Module Twice


<?
//load printBold function
include("21-1.php");


//try loading printBold function again
include("21-1.php");


printBold("Successfully avoided a second include");
?>


FreeEnergy


I used the technique of including modules on several Web applications, and it led me to
consider all the discrete elements of a Web page. Headers and footers are obvious, and so
are other repeating navigational elements. Sometimes you can divide pages up into the

Free download pdf