Designing Your Own Functions

You might be wondering why you would ever want to design a function. Functions allow your program to become a lot more robust and capable. Functions make your program modular, meaning that you can use parts of your program in other programs without worrying about problems. This means less work for you overall. Let’s take an example. Let’s say I had a program that added the numbers 1 through 10. This is how a sample program would look if I wrote it without functions:

<?php
echo "The following counter will add up the numbers 1 through 10";
echo "<br>Please wait, your numbers are being tabulated below.";
$runningcounter=0;
for ($x=1; $x <= 10; $x++)
{
    $runningcounter = $runningcounter + $x;
}
echo '<p>Your result is ' . $runningcounter;
echo "<br>Thanks for using our program!";
?>

The majority of this program is taken up by the code for the running counter. The counter also does not seem to mix well with the rest of the program that consists solely of echo statements. The program would look like the one in Figure 9.1.

Figure 9.1. A running counter program without using a function in phpft09-01.php.


As you can see, the display looks fine. Underneath, as you saw before, the code isn’t as nice as it could be. Look at how we could make this program look a heck of a lot better by turning the counter into a function:

<?php
echo "The following counter will add up the numbers 1 through 10";
echo "<br>Please wait, your numbers are being tabulated below.";
echo '<p>Your result is ' . counter_1_10();
echo "<br>Thanks for using our program!";
?>

This might look a little strange. The only change is removing the code for the for loop from the earlier program and replacing it with a function call. The call is in the echo statement.

echo '<p>Your result is ' . counter_1_10();

You can see here we changed the variable $x to counter_1_10(). Of course, this function name by itself doesn’t do anything—we need to make it actually mean something! I show you, very soon, how to make your functions work, but before I do, look at another example of using functions.

If you are writing a song, you could do something like this:

<?php
verse1();
chorus();
verse2();
chorus();
verse3();
chorus();
chorus();
?>

This is a pretty common setup for a song, but notice how you are allowed to call the same function chorus() multiple times, and in any order? Functions allow you to do cool things like this.

Before you learn how to create this program, look at the basic structure for defining a function. The parts you can change to suit your individual function are in italics.

<?php
function function_name(parameter1, parameter2,...)
{
function code
}
?>

Doesn’t seem too difficult, does it? Function definitions are just the structure and code of the function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.66.13