69
138
Chapter 5 Reusing Code and Writing Functions
Most importantly,even after you have created many pages using this header and footer,
you can easily change the header and footer files.Whether you are making a minor text
change or completely redesigning the look of the site,you need to make the change
only once.You do not need to separately alter every page in the site because each page is
loading in the header and footer files.
The example shown here uses only plain HTML in the body,header, and footer.This
need not be the case.Within these files,you could use PHP statements to dynamically
generate parts of the page.
If you want to be sure that a file will be treated as plain text or HTML,and not have
any PHP executed,you may want to use
readfile()
instead. This function echoes the
content of a file without parsing it.This can be an important safety precaution if you are
using user-provided text.
Using include()
The statements
require()
and
include()
are almost identical.The only difference
between them is that when they fail,the
require()
construct gives a fatal error,whereas
the
include()
construct gives only a warning.
Using require_once() and include_once()
There are two variations on
require()
and
include()
,called
require_once()
and
include_once()
,respectively.The purpose of these constructs is,as you might guess,to
ensure that an included file can be included only once.For the examples we have looked
at so far—headers and footers—this functionality is not particularly useful.
This functionality becomes useful when you begin using
require()
and
include()
to include libraries of functions.Using these constructs protects you from accidentally
including the same function library twice,thus redefining functions and causing an error.
Using auto_prepend_file and auto_append_file
If you want to use
require()
or
include()
to add your header and footer to every
page,you can do it another way.Two of the configuration options in the
php.ini
file are
auto_prepend_file
and
auto_append_file
.By setting these options to point to the
header and footer files,you ensure that they will be loaded before and after every page.
Files included using these directives behave as though they had been added using an
include()
statement;that is,if the file is missing,a warning will be issued.
For Windows, the settings resemble the following:
auto_prepend_file = “c:/Apache/include/header.inc”
auto_append_file = “c:/Apache/include/footer.inc”
For Unix,they resemble the following:
auto_prepend_file = “/home/username/include/header.inc”
auto_append_file = “/home/username/include/footer.inc”
59
139
Using Functions in PHP
If you use these directives, you do not need to type
include()
statements,but the head-
ers and footers will no longer be optional on pages.
If you are using an Apache web server,you can change various configuration options
like these for individual directories.To do this,you must have your server set up to allow
its main configuration file(s) to be overridden.To set up auto prepending and appending
for a directory,create a file called
.htaccess
in the directory.The file needs to contain
the following two lines:
php_value auto_prepend_file “/home/username/include/header.inc”
php_value auto_append_file “/home/username/include/footer.inc”
Note that the syntax is slightly different from the same option in
php.ini
:As well as
php_value
at the start of the line, there is no equal sign.A number of other
php.ini
configuration settings can be altered in this way,too.
Setting options in the
.htaccess
file rather than in either
php.ini
or your web serv-
er’s configuration file gives you a lot of flexibility.You can alter settings on a shared
machine that affect only your directories.You do not need to restart the web server,and
you do not need administrator access.A drawback to the
.htaccess
method is that the
files are read and parsed each time a file in that directory is requested rather than just
once at startup,so there is a performance penalty.
Using Functions in PHP
Functions exist in most programming languages;they separate code that performs a sin-
gle,well-defined task.This makes the code easier to read and allows you to reuse the
code each time you need to perform the same task.
A function is a self-contained module of code that prescribes a calling interface,per-
forms some task,and optionally returns a result.
You have seen a number of functions already.In preceding chapters,we routinely
called a number of the functions built into PHP.We also wrote a few simple functions
but glossed over the details. In the following sections,we cover calling and writing func-
tions in more detail.
Calling Functions
The following line is the simplest possible call to a function:
function_name();
This line 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 setup, and the values of various PHP and server variables.This function
does not take any parameters,and you generally ignore its return value,so a call to
phpinfo()
is simply as follows:
74
140
Chapter 5 Reusing Code and Writing Functions
phpinfo();
Most functions,however,do require one or more parameters,which are the inputs to
functions.You pass parameters by placing data or the name of a variable holding data
inside parentheses after the function name.You could call a function that accepts a single
parameter as follows:
function_name(‘parameter’);
In this case,the parameter used is a string containing only the word
parameter
,but the
following calls may also be fine depending on what parameters the function expects:
function_name(2);
function_name(7.993);
function_name($variable);
In the last line,
$variable
might be any type of PHP variable,including an array.
Aparameter can be any type of data,but particular functions usually require particular
data types.
You can see how many parameters a function takes, what each represents,and what
data type each needs to be from the function’s prototype.We often show the prototype
when we describe a function.
This is the prototype for the function
fopen()
:
resource fopen ( string filename, string mode
[, bool use_include_path [, resource zcontext]])
The prototype tells you a number of things,and it is important that you know how to
correctly interpret these specifications. In this case,the word
resource
before the func-
tion name tells you that this function will return a resource (that is,an open file handle).
The function parameters are inside the parentheses. In the case of
fopen()
,four parame-
ters are shown in the prototype.The parameters
filename
and
mode
are strings, the
parameter
use_include_path
is a Boolean,and the parameter
zcontext
is a resource.
The square brackets around
use_include_path
and
zcontext
indicate that these param-
eters are optional.You can provide values for optional parameters, or you can choose to
ignore them and the default value will be used.Note, however, that for a function with
more than one optional parameter,you can only leave out parameters from the right.For
example,when using
fopen()
,you can leave out
zcontext
or you can leave out both
use_include_path
and
zcontext
;however,you cannot leave out
use_include_path
but provide
zcontext
.
After reading the prototype for this function,you know that the following code frag-
ment is a valid call to
fopen()
:
$name = ‘myfile.txt’;
$openmode = ‘r’;
$fp = fopen($name, $openmode);
43
141
Using Functions in PHP
This code calls the function named
fopen()
.The value returned by the function will be
stored in the variable
$fp
.For this example, we chose to pass to the function a variable
called
$name
containing a string representing the file we want to open and a variable
called
$openmode
containing a string representing the mode in which we want to open
the file.We chose not to provide the optional third and fourth parameters.
Calling an Undefined Function
If you attempt to call a function that does not exist,you will get an error message,as
shown in Figure 5.3.
Figure 5.3 This error message is the result of calling a function that
does not exist.
The error messages that PHP gives are usually very useful.The one in the figure tells
you exactly in which file the error occurred, in which line of the script it occurred,and
the name of the function you attempted to call.This information should make it fairly
easy to find and correct the problem.
Check these two things if you see this error message:
n
Is the function name spelled correctly?
n
Does the function exist in the version of PHP you are using?
You might not always remember how a function name is spelled. For instance,some
two-word function names have an underscore between the words, and some do not.
The function
stripslashes()
runs the two words together,whereas the function
strip_tags()
separates the words with an underscore. Misspelling the name of a
function in a function call results in an error, as shown in Figure 5.3.
Some functions used in this book do not exist in PHP4 because this book assumes
that you are using PHP5.In each new version,new functions are defined,and if you are
using an older version,the added functionality and performance justify an upgrade.To
see when a particular function was added, you can check the online manual.Attempting
to call a function that is not declared in the version you are running results in an error
such as the one shown in Figure 5.3.
54
142
Chapter 5 Reusing Code and Writing Functions
One other reason you may see this error message is that the function you are calling
is part of a PHP extension that is not loaded.For example,if you try to use functions
from the gd (image manipulation) library and you have not installed gd, you will see this
message.
Understanding Case and Function Names
Note that calls to functions are not case sensitive,so calls to
function_name()
,
Function_Name()
,or
FUNCTION_NAME()
are all valid and all have the same result.You are
free to capitalize in any way you find easy to read, but you should aim to be consistent.
The convention used in this book,and most other PHP documentation, is to use all
lowercase.
It is important to note that function names behave differently to variable names.
Variable names are case sensitive, so
$Name
and
$name
are two separate variables, but
Name()
and
name()
are the same function.
Understanding Why You Should Define Your
Own Functions
In the preceding chapters,you saw many examples using some of PHP’s built-in func-
tions.However, the real power of a programming language comes from being able to
create your own functions.
The functions built into PHP enable you to interact with files,use a database,create
graphics, and connect to other servers.However, in your career,you often may need to
do something that the language’s creators did not foresee.
Fortunately,you are not limited to using the built-in functions; you can write your
own to perform any task that you like.Your code will probably be a mixture of existing
functions combined with your own logic to perform a task for you.If you are writing a
block of code for a task that you are likely to want to reuse in a number of places in a
script or in a number of scripts,you would be wise to declare that block as a function.
Declaring a function allows you to use your own code in the same way as the built-in
functions.You simply call your function and provide it with the necessary parameters.This
means that you can call and reuse the same function many times throughout your script.
Examining Basic Function Structure
A function declaration creates or declares a new function.The declaration begins with the
keyword
function
,provides the function name and parameters required,and contains
the code that will be executed each time this function is called.
Here is the declaration of a trivial function:
function my_function()
{
echo ‘My function was called’;
}
56
143
Examining Basic Function Structure
This function declaration begins with
function
so that human readers and the PHP
parser know that what follows is a user-defined function.The function name is
my_function
.You can call the new function with the following statement:
my_function();
As you probably guessed, calling this function results 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 func-
tions,they are available only to the script(s) in which they were declared. It is a good
idea to have a file or set of files containing your commonly used functions.You can then
have a
require()
statement in your scripts to make your functions available when
required.
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,functions,
require()
or
include()
statements,class declarations, and plain HTML. If you want to exit PHP
within a function and type plain HTML, you do so 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 preceding example and produces the same output:
<?php
function my_function()
{
?>
My function was called
<?php
}
?>
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.We
show them here because they are required within the example as well as above and
below it.
Naming Your Function
The most important point 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 follow:
n
Your function cannot have the same name as an existing function.
n
Your function name can contain only letters, digits,and underscores.
n
Your function name cannot begin with a digit.
47
144
Chapter 5 Reusing Code and Writing Functions
Many languages do allow you to reuse function names.This feature is called function over-
loading. However,PHP does not support function overloading,so your function cannot
have the same name as any built-in function or an existing user-defined function. Note
that although every PHP script knows about all the built-in functions, user-defined
functions exist only in scripts where they are declared.This means that you could
reuse a function name in a different file, but this would lead to confusion and should
be avoided.
The following function names are legal:
name()
name2()
name_three()
_namefour()
These names are illegal:
5name()
name-six()
fopen()
(The last would be legal if it didn’t already exist.)
Note that although
$name
is not a valid name for a function,a function call like
$name();
may well execute, depending on the value of
$name
.The reason is that PHP takes the
value stored in
$name
,looks for a function with that name,and tries to call it for you.
This type of function is referred to as a variable function and may occasionally be useful
to you.
Using Parameters
To do their work, most functions require one or more parameters.A parameter allows
you to pass data into a function. Here is a sample function that requires a parameter; it
takes a one-dimensional array and displays it as a table:
function create_table($data)
{
echo ‘<table border = 1>’;
reset($data); // Remember this is used to point to the beginning
$value = current($data);
while ($value)
{
echo “<tr><td>$value</td></tr>\n”;
$value = next($data);
}
echo ‘</table>’;
}
43
145
Using Parameters
If you call the
create_table()
function
$my_array = array(‘Line one.’,’Line two.’,’Line three.’);
create_table($my_array);
you see output as shown in Figure 5.4.
Figure 5.4 This HTML table is the result of calling
create_table()
.
Passing a parameter allows you to get data created outside the function—in this case,the
array
$data
—into the function.
As with built-in functions,user-defined functions can have multiple parameters and
optional parameters.You can improve the
create_table()
function in many ways,but
one way might be to allow the caller to specify the border or other attributes of the
table.Here is an improved version of the function; it is similar but allows you to option-
ally set the table’s border width, cellspacing,and cellpadding.
function create_table2( $data, $border = 1, $cellpadding = 4, $cellspacing = 4 )
{
echo “<table border = $border cellpadding = $cellpadding”
.” cellspacing = $cellspacing>”;
reset($data);
$value = current($data);
while ($value)
{
echo “<tr><td>$value</td></tr>\n”;
$value = next($data);
}
echo ‘</table>’;
}
The first parameter for
create_table2()
is still required.The next three are optional
because default values are defined for them.You can create similar output to that shown
in Figure 5.4 with this call to
create_table2()
:
create_table2($my_array);
64
146
Chapter 5 Reusing Code and Writing Functions
If you want the same data displayed in a more spread-out style,you could call the new
function as follows:
create_table2($my_array, 3, 8, 8);
Optional values do not all need to be provided; you can provide some and ignore some.
Parameters are assigned from left to right.
Keep in mind that you cannot leave out one optional parameter but include a later
listed one.In this example, if you want to pass a value for
cellspacing
,you will have to
pass one for
cellpadding
as well.This is a common cause of programming errors.It is
also the reason that optional parameters are specified last in any list of parameters.
The function call
create_table2($my_array, 3);
is perfectly legal and results in
$border
being set to
3
and
$cellpadding
and
$cellspacing
being set to their defaults.
You also can declare functions that accept a variable number of parameters.You can
find out how many parameters have been passed and what their values are with the aid
of three helper functions:
func_num_args()
,
func_get_arg()
,and
func_get_args()
.
For example,consider this function:
function var_args()
{
echo “Number of parameters:”;
echo func_num_args();
echo ‘<br />’;
$args = func_get_args();
foreach ($args as $arg)
echo $arg.’<br />’;
}
This function reports the number of parameters passed to it and prints out each of them.
The
func_num_args()
function returns the number of arguments passed in.The
func_get_args()
function returns an array of the arguments.Alternatively, you can
access the arguments one at a time using the
func_get_arg()
function,passing it the
argument number you want to access.(Arguments are numbered starting from zero.)
Understanding Scope
You might have noticed that when we needed to use variables inside a required or
included file,we simply declared them in the script before the
require()
or
include()
statement.When using a function,we explicitly passed those variables into the function
partly because no mechanism exists for explicitly passing variables to a required or
included file and partly because variable scope behaves differently for functions.
Documents you may be interested
Documents you may be interested