User-Defined Functions
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 parameter $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 ...
Get Web Database Applications with PHP and MySQL, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.