Specifications
Note that we can create variables in the main file or in the included or required file, and the
variable will exist in both. This behavior is the same for both require() and include() state-
ments.
You cannot use require() in exactly the way shown here because you cannot return values
from require() statements. Returning a value can be useful because it enables you to notify
later parts of your program about a failure, or to do some self-contained processing and return
an answer. Functions are an even better vehicle than included files for breaking code into self-
contained modules. We will look at functions next.
If you are wondering why, given the advantages of include() over require(), you would ever
use require(), the answer is that it is slightly faster.
Using Functions in PHP
Functions exist in most programming languages. They are used to separate code that performs
a single, well-defined task. This makes the code easier to read and allows us to reuse the code
each time we need to do the same task.
A function is a self-contained module of code that prescribes a calling interface, performs
some task, and optionally returns a result.
You have seen a number of functions already. In preceding chapters, we have routinely called a
number of the functions that come built-in to PHP. We have also written a few simple functions
but glossed over the details. In this section, we will cover calling and writing functions in more
detail.
Calling Functions
The following line is the simplest possible call to a function:
function_name();
This calls a function named function_name that does not require parameters. This line of code
ignores any value that might be returned by this function.
A number of functions are called in exactly this way. The function phpinfo() is often useful in
testing because it displays the installed version of PHP, information about PHP, the Web server
set-up, and the values of various PHP and server variables. This function does not take any
parameters, and we generally ignore its return value, so a call to phpinfo() will resemble the
following:
phpinfo();
Reusing Code and Writing Functions
C
HAPTER 5
5
REUSING CODE
AND
WRITING
FUNCTIONS
129
07 7842 CH05 3/6/01 3:35 PM Page 129