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) ...

Get Web Database Applications with PHP, and MySQL now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.