Specifications
Using PHP
P
ART I
118
This chapter explains how reusing code leads to more consistent, reliable, maintainable code,
with less effort. We will demonstrate techniques for modularizing and reusing code, beginning
with the simple use of require() and include() to use the same code on more than one page.
We will explain why these are superior to server side includes. The example given will cover
using include files to get a consistent look and feel across your site.
We will explain how to write and call your own functions using page and form generation
functions as examples.
In this chapter, we will cover
• Why reuse code?
• Using require() and include()
• Introduction to functions
• Why should you define your own functions?
• Basic function structure
• Parameters
• Returning a value
• Pass by reference versus pass by value
• Scope
• Recursion
Why Reuse Code?
One of the goals of software engineers is to reuse code in lieu of writing new code. This is not
because software engineers are a particularly lazy group. Reusing existing code reduces costs,
increases reliability, and improves consistency. Ideally, a new project is created by combining
existing reusable components, with a minimum of development from scratch.
Cost
Over the useful life of a piece of software, significantly more time will be spent maintaining,
modifying, testing, and documenting it than was originally spent writing it. If you are writing
commercial code, you should be attempting to limit the number of lines that are in use within
the organization. One of the most practical ways to achieve this is to reuse code already in use
rather than writing a slightly different version of the same code for a new task. Less code
means lower costs. If software exists that meets the requirements of the new project, acquire it.
The cost of buying existing software is almost always less than the cost of developing an
equivalent product. Tread carefully though if there is existing software that almost meets your
requirements. It can be more difficult to modify existing code than to write new code.
07 7842 CH05 3/6/01 3:35 PM Page 118