Specifications
This function declaration begins with function, so that human readers and the PHP parser
know that what follows will be a user-defined function. The function name is my_function.
We can call our new function with the following statement:
my_function();
As you probably guessed, calling this function will result in the text “My function was
called.” appearing in the viewer’s browser.
Built-in functions are available to all PHP scripts, but if you declare your own functions, they
are only available to the script(s) in which they were declared. It is a good idea to have one file
containing your commonly used functions. You can then have a
require() statement in all
your scripts to make your functions available.
Within a function, curly braces enclose the code that performs the task you require. Between
these braces, you can have anything that is legal elsewhere in a PHP script including function
calls, declarations of new variables or functions,
require() or include() statements, and
plain HTML. If we want to exit PHP within a function and type plain HTML, we do it the
same way as anywhere else in the script—with a closing PHP tag followed by the HTML. The
following is a legal modification of the previous example and produces the same output:
<?
function my_function()
{
?>
My function was called
<?
}
?>
Note that the PHP code is enclosed within matching opening and closing PHP tags. For most
of the small code fragment examples in this book, we do not show these tags. They are shown
here because they are required within the example as well as above and below it.
Naming Your Function
The most important thing to consider when naming your functions is that the name should be
short but descriptive. If your function creates a page header, pageheader() or page_header()
might be good names.
A few restrictions are as follows:
• Your function cannot have the same name as an existing function.
• Your function name can only contain letters, digits, and underscores.
• Your function name cannot begin with a digit.
Reusing Code and Writing Functions
C
HAPTER 5
5
REUSING CODE
AND
WRITING
FUNCTIONS
133
07 7842 CH05 3/6/01 3:35 PM Page 133