The PHP Scripting Language - User-Defined Functions (
Page 8 of 10 )
User-defined functions provide a way to group together related statements into a cohesive block. For reusable code, a function saves duplicating statements and makes maintenance of the code easier. Consider an example of a simple user-developed function as shown in Example 2-3.
Example 2-3. A user-defined function to output bold text
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd"> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Simple Function Call</title> </head>
<body bgcolor="#ffffff">
<?php
function bold($string)
{
print "<b>" . $string . "</b>";
}
// First example function call (with a static string)
print "this is not bold ";
bold("this is bold ");
print "this is again not bold ";
// Second example function call (with a variable)
$myString = "this is bold";
bold($myString);
?>
</body></html>
The script defines the function bold( ), which takes one parameter,
$string
, and prints that string prefixed by a bold
<b>
tag and suffixed with a
</b>
tag. The parame
ter
$string
is a variable that is available in the body of the function, and the value of
$string
is set when the function is called. As shown in the example, the function can be called with a string literal expression or a variable as the parameter.
Functions can also return values. For example, consider the following code fragment that declares and uses a function heading( ), which returns a string using the
return
statement:
function heading($text, $headingLevel)
{
switch ($headingLevel)
{
case 1:
$result = "<h1>$text</h1>";
break;
case 2:
$result = "<h2>$text</h2>";
break;
case 3:
$result = "<h3>$text</h3>";
break;
default:
$result = "<p><b>$text</b></p>";
}
return($result);
}
$test = "User-defined Functions";
print heading($test, 2);
The function takes two parameters: the text of a heading and a heading level. Based on the value of
$headingLevel
, the function builds the HTML suitable to display the heading. The example outputs the string:
<h2>User-defined Functions</h2>
The variable that is returned by a
return
statement can optionally be placed in paren
theses: the statements
return($result)
and
return $result
are identical.
Parameter Types and Return Types
The parameter and return types of a function aren’t declared when the function is defined. PHP allows parameters of any type to be passed to the function, and as with variables, the return type is determined when a result is actually returned. Consider a simple function that divides two numbers:
function divide($a, $b
)
{
return ($a/$b);
}
The value returned from the function divide( ) is the value of the expression
($a/$b)
. The type that is returned depends on the parameters passed to divide( ). For example:
$c = divide(4, 2); // assigns an integer value = 2
$c = divide(3, 2); // assigns a float value = 1.5
$c = divide(4.0, 2.0); // assigns a float value = 2.0
If the types of parameters passed to the function are critical, they should be tested as shown earlier in “Type Conversion.”
The
return
statement causes the execution of the function to end. To illustrate this, consider an improved divide( ) function definition that tests the parameter
$b
to avoid divide-by-zero errors:
function divide($a, $b)
{
if ($b == 0)
return false;
return ($a/$b);
}
If
$b
is 0, then the function returns
false
and the division of
$a/$b
is never executed.
The
return
statement can also be used to exit from functions that don’t return val
ues. Consider the following definition of bold( ) that simply prints the parameter
$string
without any bold mark-up when passed non-string values:
function bold($string)
{
if (! is_string($string))
{
print $string;
return;
}
print "<b>" . $string . "</b>"
;
}
Variable Scope
Variables used inside a function are different from those used outside a function. The variables used inside the function are limited to use within the function. This is called the scope of the variable. There are exceptions to this rule, which are discussed later in this section. Consider an example that illustrates variable scope:
function doublevalue($var
)
{
$temp = $var * 2;
}
$variable = 5;
doublevalue($variable);
print "\$temp is: $temp";
This example outputs the string:
$temp is:
with no value for
$temp
. The scope of the variable
$temp
is local to the function doublevalue( ) and is discarded when the function returns.
The PHP script engine doesn’t complain about an undeclared variable being used. It just assumes the variable is empty. However, this use of an undefined variable can be detected by configuring the error-reporting settings. Error reporting is discussed in Chapter 14.
The easiest way to use a value that is local to a function elsewhere in a script is to return the value from the function with the
return
statement. The calling script can simply assign the returned value to a local variable. The following example does this:
function doublevalue($var)
{
$returnVar = $var * 2;
return($returnVar);
}
$variable = 5;
$temp = doublevalue($variable);
print "\$temp is: $temp";
The example prints:
$temp is: 10
You could have still used the variable name
$temp
inside the function doublevalue( ). However, the
$temp
inside the function is a different variable from the
$temp
outside the function. The general rule is that variables used exclusively within functions are local to the function, regardless of whether an identically named variable is used else
where. There are three exceptions to this general rule: variables passed by reference, variables declared
global
in the function, and superglobals that contain user and environment values and are automatically created by PHP at runtime. Global variables are discussed in the next section, and superglobals are discussed in Chapter 6.
Global variables
If you want to use the same variable everywhere in your code, including within functions, you can do so with the global statement. The global statement declares a variable within a function as being the same as the variable that is used outside of the function. Consider this example:
function doublevalue()
{
global $temp;
$temp = $temp * 2;
}
$temp = 5
;
doublevalue();
print "\$temp is: $temp";
Because
$temp
is declared inside the function as
global
, the variable
$temp
used in doublevalue( ) is a global variable that can be accessed outside the function. Because the variable
$temp
can be seen outside the function, the script prints:
$temp is: 10
A word of caution: avoid overuse of
global
as it makes for confusing code.
The global variable declaration can be a trap for experienced program
mers. In some other languages, global variables are usually declared global outside the functions and then used in the functions.
In PHP, it’s the opposite: to use a global variable inside a function, declare the variable as global inside the function.
Allowing a function to modify global variables solves the problem that a
return
statement can only pass back one value. An alternative to using
global
is to return an array of values—this approach becomes clear when we discuss arrays in Chapter 3. A better approach is to pass parameters by reference instead of by value, a practice described later.