Functions

What is a function? A function is a block of code that can be defined once and reused in multiple parts of the program. This is a very handy tool for a programmer to have. With-out functions you would be forced to rewrite large chunks of your program every time you needed to repeat an operation. Without functions you would most likely go insane or at least you would not be coding.

Functions often take multiple parameters; a parameter is nothing more than a localized variable that the function will operate on. These parameters allow you to pass data in and out of your functions. But a function does not have to take any parameters at all. Suppose you have a function to write out the header of your HTML document; it would look something like this:

function WriteHTMLHeader()
{
    echo(“<HTML>
“);
    echo(“<HEAD><TITLE>My Application</TITLE></HEAD>
“);
    echo(“<BODY bgcolor=#ffffff>
“);
}

You declare functions by using the keyword function followed by the name you want for the function. In the above example the name of the function is WriteHTMLHeader. Techni-cally this function will not do anything at all until you invoke it from another point in the code. To invoke a function, you simply call it by name followed by any parameters it has. If the function doesn’t have any parameters, you simply leave the parentheses blank. Here is an example of calling the WriteHTMLHeader function.

// some code here
WriteHTMLHeader();
// more code

You could call this function several times in a row if you like and it would print the same HTML header to the browser every time.

Passing Parameters to a Function

Passing parameters to a function is extremely simple. All you need to do is declare a variable for each parameter you want to receive. For example, say you want a function that pops up a JavaScript error message with whatever message you pass to it.

function ErrorPopup($msg)
{
    // Create a JavaScript alert
    echo(“<SCRIPT LANGUAGE=’JavaScript’>
“);
    echo(“<!--
“);
    echo(“alert(“$msg“);
“);
    echo(“//-->
“);
    echo(“</SCRIPT>
“);
}

Now when you invoke this function you will write the following line of code:

ErrorPopup(“This is an error message!“);

As you can see, this time when you invoked the function you passed it a parameter. When the function was called, the value of the function variable $msg was set to the string, “This is an error message!”, so any time you reference $msg in the function its value will be whatever you passed in.

In the previous example the variable was passed by value, meaning that anything done to the variable in the function did not affect the value of what was passed to it. For example:

<?php
function square($num)
{
    $num *= $num;
    return $num;
}

$someNum = 6;
echo(“Variable before going into the function = “ . $someNum);
$results = square($someNum);
echo(“<br>Variable after going into the
    function = “ . $someNum . “<br>Results of
    function = “ .$results);
?>

The results of this chunk of code look like Figure 5.4.

Figure 5.4. Results of passing variables by value.


See how the value of $someNum was not affected by the operations that the function square() did? Suppose that you want the function to change the value of the variable you are passing in. How would you do that? You would pass the variable in by reference. To pass a variable into a function by reference you need to have an ampersand (&) in front of the parameter. Let’s take the same example from above and make the function change the value of the variable by passing it by reference.

<?php
function square(&$num)
{
    $num *= $num;
}

$someNum = 6;
echo(“Variable before going into the function = “ . $someNum);
square($someNum);
echo(“<br>Variable after going into the function = “ . $someNum);
?>

Figure 5.5. Results of passing variables by reference.


See how the value of $someNum changed? Its value is the result from the operations inside the function. Passing variables by reference is a very handy way to return results for multiple variables because a function can return only one value if you are using the return keyword.

Recursion

PHP functions also support recursion. Recursion is simply when a function calls itself. One of the easiest ways to explain recursion is just to show you; take this, for example:

function power($base, $exponent)
{
    if($exponent)
    {
        return $base * power($base, $exponent - 1);
    }
    return 1;
}

Notice how the return statement is calling the power function, but it is subtracting one from the variable $exponent every time it is called. Eventually $exponent will hit zero and the if statement will not execute. At this point is when the recursion ends. Take an in-depth look at how this works.

echo(power(2,3));

  1. The function power is called with the base set to 2 and the exponent set to 3.

  2. Next, the $exponent is tested; since it is non-zero it succeeds and proceeds to the next line.

  3. The return statement calls the power function again, except this time the base is 2 and the exponent is also 2.

  4. The $exponent variable is tested again. It is still a non-zero value.

  5. Power is called again with the value 2 as the base and 1 as the exponent.

  6. The exponent variable is tested again; it is still a non-zero value.

  7. Power is called a final time with the value 2 as the base and 0 as the exponent.

  8. This time the test fails and the function returns 1 to the third invocation of the function.

  9. 1 is now multiplied by the base and the third invocation of the function returns 2 to the second invocation of the function.

  10. 2 is now multiplied by the base value, giving us 4, and 4 is returned to the first invocation of the power function.

  11. 4 is now multiplied by the base, giving us the final value of 8, and 8 is returned from the power function back to your program.

Pretty confusing, huh? Recursion can be a nasty beast but you can do some pretty cool things with it.

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

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