User-Defined Functions

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.

We've already presented many examples of function calls in this chapter. Once written, a user-defined function is called in exactly the same way. Consider an example of a simple user-developed function as shown in Example 2-6.

Example 2-6. A user-defined function to output bold text
  "-//W3C//DTD HTML 4.0 Transitional//EN"
  <title>Simple Function Call</title>
<body bgcolor="#ffffff">
function bold($string)
  echo "<b>" . $string . "</b>\n";
// First example function call (with a static string)
echo "this is not bold\n";
bold("this is bold");
echo "this is again not bold\n";
// Second example function call (with a variable)
$myString = "this is bold";

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 bold( ) function, defined here, can be used with a string literal expression or a variable, as shown.

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>" . ucwords($text) . "</h1>";
  case 2:
    $result = "<h2>" . ucwords($text) . "</h2>";
  case 3:
    $result = "<h3>" . ucfirst($text) . "</h3>";
    $result = "<p><b>" . ucfirst($text) . "</b>";
$test = "user defined functions";
echo 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-changing the case of the $text appropriately. The previous fragment generates the string:

<h2>User Defined Functions</h2>

The variable that is returned by a return statement can optionally be placed in parentheses: the statements return($result) and return $result are identical.