Using Parameters and Function Values

Using Parameters and Function Values

Functions are meant to be self-contained. This is good because the entire program can be too complex to understand. If you break the complex program into smaller functions, each function can be set up to work independently. When you work inside a function, you don't have to worry about anything outside the function. If you create a variable inside a function, that variable dies as soon as you leave the function. This prevents many errors that can otherwise creep into your code. The bad side of functions being so self-contained is you often want them to work with data from the outside program. There are a couple of ways to do this. You can send a parameter to a function, which allows you to determine one or more values sent to the function as it starts. Each function can also have a return value. An example will make this more clear. The param program, shown in Figure 3.13 illustrates another form of the This Old Man song. Although again the user might not be aware of it, there are some important differences between this more sophisticated program and the first This Old Man program.

Click To expand
Figure 3.13: While the output looks similar to Figure 3.12, the program that produced this page is much more efficient.

Examining the Param.php Program

Notice that the output of Figure 3.13 is longer than that of 3.12, but the code that generates this longer output is shorter and more efficient.

<html>
<head>
<title>Param Old Man</title>
</head>
<body>
<h1>Param Old Man </h1>
<h3>Demonstrates use of function parameters</h3>
<?

print verse(1);
print chorus();
print verse(2);
print chorus();
print verse(3);
print chorus();
print verse(4);
print chorus();

function verse($stanza){
  switch ($stanza){
    case 1:
      $place = "thumb";
      break;
    case 2:
      $place = "shoe";
      break;
    case 3:
      $place = "knee";
      break;
    case 4:
      $place = "door";
      break;
    default:
      $place = "I don't know where";
  } // end switch

  $output = <<<HERE
  This old man, he played $stanza<br>
  He played knick-knack on my $place<br><br>
HERE;
  return $output;
} // end verse

function chorus(){
  $output = <<<HERE
  ...with a knick-knack<br>
  paddy-whack<br>
  give a dog a bone<br>
  this old man came rolling home<br>
  <br><br>
HERE;
  return $output;
} // end chorus

?>
</body>
</html>

Looking at Encapsulation in the Main Code Body

This code features a number of improvements over the previous version. First, look at the main body of the code that looks like this:

print verse(1);
print chorus();
print verse(2);
print chorus();
print verse(3);
print chorus();
print verse(4);
print chorus();

The main code body is very easy to understand. The program is to print the first verse, then the chorus, then the second verse, then the chorus, and so on. The details of how all these things are to be generated is left to the individual functions. This is an example of encapsulation. Encapsulation is good, because it allows you to think about problems in multiple levels. At the highest level, you're interested in the main ideas (print the verses and chorus) but you're not so concerned about the exact details. You use the same technique when you talk about your day: "I drove to work, had some meetings, went to lunch, and taught a class." You don't usually describe each detail of each task. Each major task can be broken down into its component tasks later. (If somebody asks, you could really describe the meeting: "I got some coffee, appeared to be taking notes furiously on my palm pilot, got a new high score on Solitaire while appearing to take notes, scribbled on the agenda, and dozed off during a presentation.")

Returning a Value: The chorus() Function

Another interesting thing about the main section of code is the use of the print() function. In the last program, I simply said chorus() and the program printed the verse. In this program, I did it a little differently. The chorus() function doesn't actually print anything to the screen. Instead, it creates the chorus as a big string and sends that value back to the program, which can do whatever it wants with it. This behavior isn't really new to you. Think about the rand() function. It always returns a value back to the program. The functions in this program work in the same way. Take another look at the chorus() function to see what I mean.

function chorus(){
  $output = <<<HERE
  ...with a knick-knack<br>
  paddy-whack<br>
  give a dog a bone<br>
  this old man came rolling home<br>
  <br><br>
HERE;
  return $output;
} // end chorus

I began the function by creating a new variable called $output. You can create variables inside functions by mentioning them, just like you can in the main part of the program. However, a variable created inside a function loses its meaning as soon as the function is finished. This is good, because it means the variables inside a function belong only to that function. You don't have to worry about whether the variable already exists somewhere else in your program. You also don't have to worry about all the various things that can go wrong if you mistakenly modify an existing variable. I assigned a long string (the actual chorus of the song) to the $output variable with the <<<HERE construct.

The last line of the function uses the return statement to send the value of $output back to the program. Any function can end with a return statement. Whatever value follows the keyword return will be passed to the program. This is one way your functions can communicate to the main program.

Accepting a Parameter in the verse() Function

The most efficient part of this newer program is the verse() function. Rather than having a different function for each verse, I wrote one function that can work for all the verses. After careful analysis of the song, I noticed that each verse is remarkably similar to the others. The only thing that differentiates each verse is what the old man played (which is always the verse number) and where he played it (which is something rhyming with the verse number). If there is some way to indicate which verse to play, it should be easy enough to produce the correct verse. Notice that when the main body calls the verse function, it always indicates a verse number in parentheses. For example, it makes a reference to verse(1) and verse(3). These commands both call the verse function, but they send different values (1 and 3) to the function. Take another look at the code for the verse() function to see how the function responds to these inputs.

function verse($stanza){
  switch ($stanza){
    case 1:
      $place = "thumb";
      break;
    case 2:
      $place = "shoe";
      break;
    case 3:
      $place = "knee";
      break;
    case 4:
      $place = "door";
      break;
    default:
      $place = "I don't know where";
  } // end switch

  $output = <<<HERE
  This old man, he played $stanza<br>
  He played knick-knack on my $place<br><br>
HERE;
  return $output;
} // end verse

In this function, I indicated $stanza as a parameter in the function definition. A parameter is simply a variable associated with the function. If you create a function with a parameter, you are required to supply some sort of value whenever you call the function. The parameter variable automatically receives the value from the main body. For example, if the program says verse(1), the verse function will be called, and the $stanza variable will contain the value 1.

I then used a switch statement to populate the $place variable based on the value of $stanza. Finally, I created the $output variable using the $stanza and $place variables and returned the value of $output.

TRICK?

You can create functions with multiple parameters if you wish. Simply declare several variables inside the parentheses of the function definition, and be sure to call the function with the appropriate number of arguments. Make sure to separate parameters with commas.

IN THE REAL WORLD
Start example

If you're an experienced programmer, you probably know there are other ways to make this code even more efficient. We'll come back to this program as you learn about loops and arrays in the coming chapters.

End example