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
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Simple Function Call</title>
</head>
<body bgcolor="#ffffff">
<?php
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";
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
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) ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access