[ Team LiB ] Previous Section Next Section

Defining a Function

You can define a function using the function statement:


function some_function( $argument1, $argument2 ) {
   // function code here
}

The name of the function follows the function statement and precedes a set of parentheses. If your function is to require arguments, you must place comma-separated variable names within the parentheses. These variables are filled by the values passed to your function. If your function requires no arguments, you must nevertheless supply the parentheses.

Listing 6.2 declares a function.

Listing 6.2 Declaring a Function
 1: <!DOCTYPE html PUBLIC
 2:    "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 6.2 Declaring a Function</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: function bighello() {
12:   print "<h1>HELLO!</h1>";
13: }
14: bighello();
15: ?>
16: </div>
17: </body>
18: </html>

The script in Listing 6.2 simply outputs the string "HELLO" wrapped in an HTML <h1> element. We declare a function, bighello(), that requires no arguments. Because of this, we leave the parentheses empty. bighello() is a working function but is not terribly useful. Listing 6.3 creates a function that requires an argument and actually does something helpful with it.

Listing 6.3 Declaring a Function That Requires Arguments
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 6.3 Declaring a Function That Requires Arguments</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: function printBR( $txt ) {
12:   print ( "$txt<br />\n" );
13: }
14: printBR("This is a line");
15: printBR("This is a new line");
16: printBR("This is yet another line");
17: ?>
18: </div>
19: </body>
20: </html>

You can see the output from the script in Listing 6.3 in Figure 6.1. In line 11, the printBR() function expects a string, so we place the variable name $txt between the parentheses when we declare the function. Whatever is passed to printBR() is stored in $txt. Within the body of the function, in line 12, we print the $txt variable and append a <br /> element and a newline character to it.

Figure 6.1. A function that prints a string with an appended <br /> tag.

graphics/06fig01.gif

Now when we want to write a line to the browser, such as in line 14, 15, or 16, we can call printBR() instead of the built-in print(), saving us the bother of typing the <br /> element.

    [ Team LiB ] Previous Section Next Section