Specifications

Reliability
If a module of code is in use somewhere in your organization, it has presumably already been
thoroughly tested. Even if it is only a few lines, there is a possibility that if you rewrite it, you
will either overlook something that the original author incorporated or something that was
added to the original code after a defect was found during testing. Existing, mature code is
usually more reliable than fresh, green code.
Consistency
The external interfaces to your system, including both user interfaces and interfaces to outside
systems, should be consistent. It takes a will and a deliberate effort to write new code that is
consistent with the way other parts of the system function. If you are re-using code that runs
another part of the system, your functionality should automatically be consistent.
On top of these advantages, re-using code is less work for you, as long as the original code
was modular and well written. While you work, try to recognize sections of your code that you
might be able to call on again in the future.
Using require() and include()
PHP provides two very simple, yet very useful, statements to allow you to reuse any type of
code. Using a require() or include() statement, you can load a file into your PHP script.
The file can contain anything you would normally type in a script including PHP statements,
text, HTML tags, PHP functions, or PHP classes.
These statements work similarly to the Server Side Includes offered by many Web servers and
#include statements in C or C++.
Using require()
The following code is stored in a file named reusable.php:
<?
echo “Here is a very simple PHP statement.<BR>”;
?>
The following code is stored in a file called main.php:
<?
echo “This is the main file.<BR>”;
require( “reusable.php” );
echo “The script will end now.<BR>”;
?>
Reusing Code and Writing Functions
C
HAPTER 5
5
REUSING CODE
AND
WRITING
FUNCTIONS
119
07 7842 CH05 3/6/01 3:35 PM Page 119