Search This Blog

Wednesday, March 31, 2010

The Include and Require Statements

Another way to make your code easier to use and maintain is to use include files. Actually, you've used them several times already and have seen how easy it is to bring external files into the current script and run them. All you have to do is use either the include or require constructs (remember, they're language constructs, not functions, even though they are called in a similar fashion) with the name of the file you want to bring in, and that's that. The only difference between the two is how they handle failure to bring in the external file. A failure of include results in a warning; a failure of require results in a fatal error.


There are a few fine points about how they work:
  • You include or require a file by inserting the construct within PHP code, but parsing drops out of PHP mode and into HTML mode at that point, so you still have to put the code in the included file inside proper PHP delimiters to make it run.
  • You may include or require a file from within a function, but if so, any variables created in the code in the included file have local scope within the function.
  • The PHP script within the include file is evaluated (run) when it is included. Any PHP variables that have values are available in the main file, just as though the entire block of code had been directly written inside the file.
Here are a few examples of how to write these constructs in your code (you can include full absolute or relative paths if you like):


include("filename")
require ("filename");

For example, to include the file test.txt, you would type:


include("test.txt");

If the file test. txt contained the text "Hello", then this text would be included on the Web page, just as though it had been coded directly into it.


Interestingly, within the include or require functions you can also add variable names or concatenate them to the name of the filename, inside the brackets, as long as it creates a legal file name:


$Name ="1";
include ("test" . $Name . ".txt");

The result of this concatenation is test1.txt, and if there is a file of that name, it will be included—otherwise an error is generated.


So when are include files handy? Use them to:
  • Include text files in the page.
  • Define variables and/or constants and details of certain error messages.
  • Insert the values of HTTP variables in the page.
  • Execute a separate PHP script (even when it may return nothing).
  • Place commonly used functions that you need but don't want to define in every page.
Include files are useful in that they can be added directly to a file, but you can create code that decides whether that file should be included or not. That's exactly what you're going to do in the next example.


Try it Out: Conditional Includes
Start example
  1. Start up your Web page editor and type in the following words:
    File One included
    
  2. Save this as a text file and call it file1.txt.
  3. Close it and create a new text file and type in the following:
    File Two included
    
  4. Save this as a text file and call it file2.txt.
  5. Now close that file, start another new file, and type in the following:
    <html>
    <head><title></title></head>
    <body>
    <?php
    if (isset($_POST['posted'])) {
       $choice = $_POST['choice'];
       if ($choice <> "") {
          include("file" . $choice . ".txt");
          echo "<hr>";
       }
    }
    ?>
    <form method="POST" action="include.php">
    <input type="hidden" name="posted" value="true">
    What file do you wish to include?
    <select name="choice">
    <option value="1">file one</option>
    <option value="2">file two</option>
    </select>
    <br>
    <br>
    <input type="submit" value="Get Text">
    </form>
    </body>
    </html>
    
  6. Save this as include.php in the same place as the two text files.
  7. Open include.php in your browser and make a choice. 


End example

How it Works

First a little form is created to offer the user two choices in a drop-down box named "choice". Then, when the following code runs, it simply checks to see which value was chosen (if you chose file one, for example, the value provided was 1) and uses that value to construct the filename to include.


<?php
if (isset($_POST['posted'])) {
   $choice = $_POST['choice'];
   if ($choice <> " ") {
      include("file" . $choice . ".txt");
      echo "<hr>";
   }
}
?>

Of course, you'd already made the text files file1.txt and file2.txt and entered a little bit of text in them (otherwise you'd have gotten an error message. Did you?).

Monday, March 29, 2010

Scope of Variables

Scope was discussed a bit in Chapter 2, and now that discussion expands. You can create variables in a PHP script both external to a function (outside the function) and internal to the function (inside the function). If you create a variable named $total_sales outside a function, for example, and then pass its value inside a function that performs processing on an internally created variable named $total_sales, you have two distinct variables named $total_sales in existence in your script.Obviously, this situation is not going to work unless the two variables stay separate. So PHP uses the concept of scope (like so many other languages), and differentiates between the two variables so it doesn't get mixed up.


If you think about it, there are many situations where it would be convenient to use variables with the same name in one script or program. Scope allows PHP to work with two variables of the same name, so long as they remain in their appropriate places. (In much the same way, namespaces provide a means for XML elements of the same name to work within the same XML document and still stay separate. XML namespaces are discussed in Chapter 8.)


Variables created in a PHP script have a lifetime as well as scope. A variable created inside a function stays in existence only as long as the function is processing. When the function finishes, the variable is lost, unless you define it as a static variable (more on static variables a little later in the chapter). So you say the scope of the variable is inside the function, and the lifetime of the variable is as long as the function is performing its work (a new inside variable is created each time the function is called, and it has a new life). All variables in a PHP script reach the end of their lives when the script is done.

Global and Local Variables

Variables that are created outside a function remain alive until the script ends, and are therefore said to have global scope, meaning they can be accessed from anywhere in the script. However, to access them within a function, you must use the global keyword. Placing the keyword global before the name of a variable means that you can use it within the function (but you can't then create another variable of the same name because that name is now taken within the function as well). Variables that are created inside a function are described as having local scope.


Here's an example of how local and global variables work:


<?php
$global_message = "Global Message";
function addto_message($global_message)
{
   global $global_message;
   $global_message .= " And More";
   return $global_message;
}
addto_message ($global_message);
echo "the global messge is " . $global_message;
?>

This example produces a statement with the value "The global message is Global Message And More" because running the function changes the value of $global_message. It only changes because the global keyword is used; it's almost like passing the argument into the function by reference.


In fact, putting the global keyword in front of a variable name inside the function does reference a superglobal array variable named $_GLOBALS. In this case, creating the variable $global_message (or any variable, for that matter) in the PHP script outside the function (and thereby with global scope) automatically sets it as part of the $_GLOBALS variable. So there are really two ways to access global variables from inside a function: by preceding their names with the global keyword (like this: global $global_message), or by using $_GLOBALS superglobal array variable (like this: $_GLOBALS[global_message]).

Creating Static Function Variables

You'll recall from Chapter 2 that creating a variable inside a function with the keyword static in front of it allows that variable to persist beyond the time the function runs. And because the static variable exists only in the local scope of the function, both the variable and its most recently accumulated value will be available next time the function runs. This can be useful anytime you want to count something that happens or is measured within the function.
For example, suppose you want to count the records returned each time records are retrieved from a database. You could write something like this:


<?php
function get_records($table)
{
   //make database connection
   //retrieve records
   //get_record_count
   static $record_count;
   //set $record_count equal to number of records returned, plus any current
   //value it holds
   echo "current total records retrieved is " . $record_count;
   //return something }

Although the example is mostly pseudo code, it shows how to set the $record_count variable so that it is static. And it should be clear that each time the function runs (at least, as long as the PHP script is running), the $record_count variable will be incremented by the number of records returned. For example, if you retrieved 20 records the first time, 30 records the second time, and 40 records the last time the function was called within a PHP script, then $record_count would be set to 90 by the end of the script. Of course, you could echo out the current record count each time, as this example did.


Here's a quick recap of global, local, and static variables:
  • Global variables have values that persist throughout the whole program, but to use them inside a function you have to prefix them with the keyword global or address them using the $_GLOBALS superglobal array.
  • Local variables have values that exist only inside of a function and only for the duration of one function call.
  • Static variables are local variables that persist in value inside the function every time the function is called.
Next, create a small application that demonstrates how these work.


Try it Out: Demonstrating Scope
Start example
  1. Open your Web page editor and enter in the following:
    <html>
    <head><title></title></head>
    <body>
    
    <font size=-1>
    <?php
    $global_message = "Global Message";
    function my_function()
    {
       $local_message = "Local Message";
       static $static_number = 0;
       echo "<br>the contents of global message are " . $GLOBALS["global_message"];
       echo "<br>the contents of local message are " . $local_message;
       echo "<br>the contents of static number are " . $static_number;
       return $static_number = $static_number+1;
    }
    echo "<b>Calling the function for the first time:</b>";
    my_function();
    
    echo "<br><br><b>Outside the function:</b>";
    echo "<br>the contents of global message are " . $global_message;
    echo "<br>the contents of local message are " . $local_message;
    echo "<br>the contents of static number are " . $static_number;
    echo "<br><br><b>Calling the function for the second time:</b>";
    
    my_function();
    echo "<br><br><b>Outside the function: </b>";
    echo "<br>the contents of global message are " . $global_message;
    echo "<br>the contents of local message are " . $local_message;
    echo "<br>the contents of static number are " . $static_number;
    echo "<br><br><b>Calling the function for the third time:</b>";
    
    my_function();
    echo "<br><br><b>Outside the function:</b>";
    echo "<br>the contents of global message are " . $global_message;
    echo "<br>the contents of local message are " . $local_message;
    echo "<br>the contents of static number are " . $static_number;
    ?>
    </font>
    </body>
    </html>
    
  2. Save this as scope.php. and close the file.
  3. Open up your browser and render scope.php.


End example

How it Works

This program has no practical application, but given that variable scope is a difficult subject to grasp, the program emphasizes how the different types of variables work in PHP. The first line creates and assigns $global_message:


$global_message = "Global Message";

The function (named my_function) is defined:


function my_function()
{


Inside it, a local variable, called $local_message, and a static variable called $static_number, are created:


$local_message="Local Message";
static $static_number = 0;

The next three lines display the contents of the global, local, and static variables within the function:


echo "<br>the contents of global message are " . $GLOBALS["global_message"];
echo "<br>the contents of local message are " . $local_message;
echo "<br>the contents of static number are " . $static_number;

The return statement alters the contents of the $static_number variable, incrementing it by 1:


      return $static_number = $static_number+1;
}

The program starts by calling my_function():


echo "<b>Calling the function for the first time:</b>";
my_function();

You see the contents of the global, local, and static variables, which are "GlobalMessage", "Local Message", and 0 inside the function. Once the function is finished running, the contents of these variables are shown outside the function. You may get undefined variable warnings, depending on what level of error reporting you have set—this is normal if you think about it. $local_message and $static_number are only defined within the function body, and so do not exist outside of it:


echo "<br><br><b>Outside the function:</b>";
echo "<br>the contents of global message are " . $global_message;
echo "<br>the contents of local message are " . $local_message;
echo "<br>the contents of static number are " . $static_number;
The function is called several more times, and each time shows what the variables inside the function are set to, as well as what they are outside the function. The $static_number variable inside the function is the only one that changes.

Nesting

It's possible to create and call functions within functions. This is called nesting, but under most circumstances this capability isn't very useful. You've already looked at calling functions from within functions, and by itself this is helpful. But to define and call a function inside a function can lead to problems.


For example, you could write a parent function that would, within itself, define another function (call it the child function). The problem is that if you call the parent function twice, you're in effect trying to define the child function twice, and you can't redefine existing functions, so the script would fail. Mostof the time you're better off just defining functions separately.


But there is another situation (besides using functions for switching, as discussed a few sections ago) when it would be useful to call a function from inside a function: recursion (a function calling itself).

Recursion

Calling a function from within itself is known as recursion. Calling a function recursively creates a looping structure, in that the function will continue to call itself until a condition is met. However, you have to create the condition explicitly within the lines of code in the function, and if you don't ensure that there is some kind of "stop" value that will be reached no matter what, your function may recurse (and you may curse a few times yourself) infinitely. Here's a quick example.


Try it Out: Calling a Function Recursively
Start example
  1. Start up your Web page editor and type the following:
    <html>
    <head></head>
    <body>
    <?php
    
    if {$._POST[posted]) {
       $num - $_POST[num];
       function, recursion ($num) {
          if ($num <= 1) {
             return 1;
          } else{
             return $num * recursion($num-1);
          }
       }
       echo "The factorial of " . $num . " is " . (recursion($num));
    }
    ?>
    <form method="POST" action="recursion.php">
    <input type="hidden" name="posted" value="true">
    I would like to know the factorial of
    <input name="num" type="text">
    <br>
    <br>
    <input type="submit" value="Get Factorial">
    </form>
    </body>
    </html>
    
  2. Save this as recursion.php and close the file.
  3. Open recursion.php in your browser. 


End example
Of course, once you have chosen your value and pressed the Get Factorial button, the faithful recursive example tells you the answer.

How it Works

First declare the recursion function, and give it $num_value as an argument:


<?php

if ($_POST[posted]) {

   $num = $_POST[num];
   function recursion($num) {
      if ($num <= 1) {
         return 1;
      } else {
         return $num * recursion($num-1);
      }
   }
   echo "The factorial of " . $num . " is " . (recursion($num));
}
?>

Next, make sure that $num has not been given as zero or one; if it has, you return 1 (you already know that the factorial of one is one). If you have a number greater than one, execute the recursive part of the function. Finally, you echo the result.


Each time through the loop you not only multiply by the most recent number (that's the recursive part), but you also use the steadily dwindling value to make sure the loop eventually ends. (It's easy to break the script with larger numbers, and that it doesn't work with negative numbers, but for this example, it works well enough.)

Saturday, March 27, 2010

Writing User-Defined Functions in PHP

PHP contains quite a number of built-in functions, such as isset(), strlen(), and so on. And although built-in functions always accomplish very useful tasks, you can be sure that not every possible function can exist in any version of PHP, even in future versions. So suppose you need a function that doesn't exist in PHP. That's where user-defined functions come into the picture—essentially you have the capability to author your own functions, and make them do whatever you want!


Any functions that you create are called user-defined functions. You use the function keyword to define a function and, once defined, that function may be used anyplace in your code, simply by calling its name. When combined with the capability to include files, functions become a very powerful tool in your programming arsenal.


Functions enable you to encapsulate sections of code as though they were independent stand-alone programs. You can pass values into them, and get values out of them. You can call functions at any time during your PHP script, and redirect the flow of execution in this way.
Functions also introduce the idea of scope (fully discussed later in this chapter) into your programs. The normal process in your PHP programs is that once a variable is created, the name you have assigned to it, and the value, persist until you alter it or until the script ends. However, in functions you have to learn to deal with the idea that variables might only exist inside a function, whereas outside it they have no value.


In this chapter you'll build some functions that will work on the same principle as the readymade ones you've already used: when you supply them with information, they will perform an operation and return an answer.

The Structure of Functions

Functions are sections of code that are defined by the user to perform a specific task, and given a name by which to call them. You already know that functions can take values called arguments as input, perform some operations, and then may return another value. The function transfers any argument values into new variables called parameters, which can then be used within the function. You've used PHP's built-in functions extensively in this book so far; to do things like get the data type of a variable (gettype()) right through to sorting arrays (sort()). Writing your own function means you get to give it your own made-up name, but you call it the same way as calling the built-in functions.
Take a look at how functions work, step-by-step:
  1. The function is written with a name followed by parentheses. Inside the parentheses are the names of any values the function accepts (these values, called arguments, are optional), written as variable names (preceded by a dollar sign like any normal variable) and separated by commas.
  2. The function is called by writing its name and parentheses. If the function requires any arguments, they are included within the parentheses and are separated by commas. Arguments may be variables or hard-coded values, and do not have to be the same as the variable names in the argument list in the defined function.
  3. When the function is called, arguments passed to it are turned into parameters, and the parameters are used inside the function to perform the data processing specified by the function. Think of parameters as placeholders for values being passed into the function.
  4. The return keyword may be used to pass values back out to the calling code after data processing is complete inside the function. Returning values is optional; some functions just do their work and then end without any further notification required. However, it is a good idea to at least return a true or false value to indicate to the rest of your code whether the function successfully completed its work.
  5. If a value is passed back out of the function, it can be expressed using the echo statement, or it can be assigned to a variable outside the function.

Defining and Calling Functions

You begin creating a function by writing the function keyword followed by a space and then the name you want the function to be addressed by. If you want your function to accept arguments (it doesn't have to), list them in parentheses after the name of the function. Then the code that runs when the function is called is placed within curly braces, the same way you delimit blocks of code in conditional structures. Here's the syntax:


function functionname (parameters)
{
   //put your function code here
}
For example, if you want to write a function that calculates a bonus, code such as this would do:
function bonus($sales)
{
   $bonus = $sales * 0.15;
   return $bonus;
}

Notice the return statement in this example. If your function simply records something in a database, there may not be any return value. If you want the function to send data back out, you must use the return statement, in the manner shown. For example, this is what it would look like if you had some code calling your newly defined function:


$my_total_sales = 120499;
//find out my bonus, based on my total sales
$my_bonus = bonus($my_total_sales);

Because the example returns the result of the calculation on the incoming value (in this case, $120,499), as set in the variable $my_total_sales), the variable $my_bonus will end up being set equal to the outgoing value returned by the function.


You can put as many lines of code as you want in a function, and a line of code can do anything within the bounds of what PHP can ordinarily do: connect to a database, open a file, match a regexp pattern, and so on. You can also make the function echo text out, or print something to the screen.


The return statement, by itself, doesn't display a value; it just passes the result (if any) to the function. The process of executing the contents of a function within a PHP script is known as calling the function.


You can supply a function directly with a number:


echo (bonus(120499));
or you can furnish the function with the name of an already created variable:
$total_sales=120499;
echo (bonus($total_sales));
You can supply more than one parameter to the function, but you must separate each parameter with a comma as illustrated here:
function bonus($total_sales, $bonus_factor)
{
   $bonus = $total_sales * $bonus_factor;
   return $bonus;
}

To call the modified bonus function, you'd supply two values: total_sales and bonus_factor, like this:


$total_sales = 120000;
$bonus_factor = 0.15;
echo (bonus($total_sales, $bonus_factor));

Functions can be defined anywhere within your PHP program. It's common to define functions in a separate file and simply include (or require) that file at the beginning of the main processing file you're creating. You don't need to define or initialize your variables before you define your function; you do, however, need to make sure they are defined or initialized before you call the function.


For example, the following code works:


<?php
$total_sales = 190999;             // Execution will start here
$bonus_factor = 0.15;
echo (bonus($total_sales, $bonus_factor)};   // Function called here
function bonus($total_sales, $bonus_factor)  // Function defined here
{
   $bonus = $total_sales * $bonus_factor;
   return $bonus;
)
?>
But the following also works just fine:
<?php
function bonus($total_sales, $bonus_factor) // Function defined here
{
   $bonus = $total_sales * $bonus_factor;
   return $bonus;
}
$total_sales = 190999;            // Execution will start here
$bonus_factor = 0.15;
echo (bonus($total_sales, $bonus_factor));  // Function called here
?>

And here's an important note about the way functions work. You can use any variable names outside the function to pass values inside the function. For example, suppose instead of using exactly the same names ($total_sales and $bonus_factor) both outside and inside the bonus function, you used $out_total_sales and $out_bonus_factor for the variables that exist outside the function, and $in_total_sales and $in_bonus_factor for the variable inside the function. It would work just fine, and would simply look like this:


<?php
function bonus($in_total_sales, $in_bonus_factor) // Function defined here
{
   $bonus = $in_total_sales * $in_bonus_factor;
   return $bonus;
}
$out_total_sales = 190999;            // Execution will start here
$out_bonus_factor = 0.15;
echo (bonus($out_total_sales, $out_bonus_factor));  // Function called here
?>

Now take another look at parameters and how they work. When you write a function and define it with one or more variables within the parentheses following the function name, the variables are said to be arguments. When you actually call a function and send data into it (as arguments to the function), the values in the arguments (whether they come in as variables or as hard-coded values) are turned into parameters. Parameters are like temporary variables inside a function, and whereas they are being processed within the function (and perhaps take on new values during processing) they remain parameters.


After the resulting values of processed parameters are passed back out of the function, the parameters vanish. What parameters do (appear when the function is called and then disappear when the function completes processing) is completely unrelated to any variables you might create inside the function.


Before you write another user-defined function as a working example, here's a recap:
  • User-defined functions are named by the developer.
  • Functions may take parameters, which are values or variables defined in parentheses after the function name.
  • Multiple parameters are separated by commas.
  • The code of the function body is provided in braces after the function name and parameters.
  • You must use the return keyword inside the function to return a value that you can use outside the function.
  • If there is no value to return, the return keyword just denotes the end of the function code.
  • Functions aren't actually executed until called from a line of code within your PHP script.
  • You may call a function either before or after it appears in the code—it doesn't matter where you put a function in your code.
  • You can call a function as few or as many times as you need, and you can send any values you like into the function, sending them as hard-coded values or as values inside their own variables.
That last item in the recap list should clue you in about code reuse; not having to rewrite the lines of code processed by a function every time you need those lines of code to run is a major savings in coding and debugging effort.


Now take the holiday.php example code from earlier chapters and write a function to calculate the expenses for the holiday break week. You'll see that you end up saving quite a few lines of code.


Try it Out: Using a Simple Function
Start example
  1. Enter the following code and save it as holiday3.php (you can use sections of your previously written code to save time if you like):
    <html>
    <head><title></title></head>
    <body>
    <b>Namllu Holiday Booking Form</b>
    <?php
    function calculator($price, $city_modifier, $star_modifier)
    {
       return $price = $price * $city_modifier * $star_modifier;
    }
    if (isset($_POST['posted'])) {
       $price = 500;
       $star_modifier = 1;
       $city_modifier = 1;
       $destgrade = $_POST['destination'].$_POST['grade'];
       switch($destgrade) {
          case "Barcelonathree";
             $city_modifier = 2;
             break;
          case "Barcelonafour";
             $city_modifier = 2;
             $star_modifier = 2;
             break;
          case "Viennathree";
             $city_modifier = 3.5;
             break;
          case "Viennafour";
             $city_modifier = 3.5;
             $star_modifier = 2;
             break;
          case "Praguethree";
             break;
          case "Ppraguefour";
             $star_modifier = 2;
             break;
          default;
             $city_modifier = 0;
             echo ("Please go back and try it again");
          break;
       }
       if ($city_modifier <> 0)
       {
          echo "The cost for a week in $_POST[destination] is " . "$" .
    calculator($price, $city_modifier, $star_modifier);
       }
    }
    ?>
    <form method="POST" action="holiday3.php">
    <input type="hidden" name="posted" value="true">
    Where do you want to go on holiday?
    <br>
    <br>
    <input name="destination" type="radio" value="Prague">
    Prague
    <br>
    <input name="destination" type="radio" value="Barcelona">
    Barcelona
    <br>
    <input name=="destination" type="radio" value="Vienna"> Vienna
    <br>
    <br>
    What grade of hotel do you want to stay at?
    <br>
    <br>
    <input name="grade" type="radio" value=" three ">
    Three star
    <br>
    <input name="grade" type="radio" value="four">
    Four star
    <br>
    <br>
    <input type="submit" calue=" Check Prices"> </form>
    </body>
    </html>
    
  2. Save and close the file
  3. Open holiday3.php in your browser, enter some choices, and submit the form. The holiday3.php example should work just fine:


End example

How it Works

The holiday form should be very familiar by now, it's simply capturing two variables from the user via the $_POST variable ($_POST[destination] and $_POST[grade]) and passing them along to the PHP script. The PHP code starts with the function (named calculator) to calculate the cost of our holiday:


function calculator($price, $city_modifier, $star_modifier)
{
   return $price = $price * $city_modifier * $star_modifier;
}

The user-defined calculator() function takes three parameters: the basic price of the holiday, the adjustment to the price for the chosen city, and the final adjustment for the star rating of the hotel. It multiplies these three variables together and returns one value ($price), the total price of the hotel.


The rest of the program works the same as before, concatenating destination and grade into a single value that is used to switch through the various options. There is one small change within the default option, though: the content of the $city_modifier variable is changed to zero if none of the cases are executed. Before executing the calculator() function, you check to see whether the $city_modifier variable has been set to 0; if it hasn't, you can call the function within the echo() statement, using the concatenate operator (the period) to add text to your function result:


if ($city_modifier <> 0)
{
   echo "The cost for a week in $_POST[destination] is " . "$" .
   calculator($price, $city_modifier, $star_modifier);
}

Switching Functions

In the same way that you can use the switch structure to switch among various processing options within a PHP program, you can write your own functions that accept incoming values and, based on those values, switch among various other functions for processing. This is a very powerful feature of user-defined functions in PHP.


Here's a quick example. Suppose you want to create an application that pulls records from various tables in a database. You might send an input value in a variable called $ table_name to the switching function, and within that function decide which query function to run, as shown in this code:


function query switch($table_name)
{
   switch ($table_name) {
      case "clients":
         $query = query__clients_gen());
            break;
      case "orders":
         $query = query_orders_gen());
            break;
      case "employees":
          $query = query_employees_gen()) ;
          break;
      default:
         echo "Please select a table name";
   }
}
function query_client_gen()
{
   //composes a database query to select records from the clients table
}
function query_orders_gen()
{
   //composes a database query to select records from the orders table
}
function query_employees_gen()
{
   //composes a database query to select records from the employees table
}

The beauty of using this type of structure is that you can place the functions you've written into an include file, and then include the functions in any page, making it easy to add the composition of database queries to any page you like. In addition, you only need to change the code once if you're making an improvement to it, and the code is easier to read through. In fact, once you're confident that the functions do what you intend, you don't really have to read through them as you're coding, you can just call them whenever you need them.


Because you can assign the result of a function (one that has a return value) directly to a variable, you can simply use the result of a function in a switch..case statement. For example, suppose you create a small management function that tells you how many hits occurred on a page. You can take the number of hits returned by the function and use it to echo out an easy-to-understand message to the user, as this code shows:


switch ($hit_counter = get_hits ($current_page)) {
   case $hit_counter <100:
      echo "Few hits today";
      break;
   case $hit_counter <1000:
      echo "Lots of hits today";
      break;
   case $hit_counter <:10000:
      echo "Too many hits today";
      break; }

The variable $hit_counter would then be able to store whatever the function get_hits($current_page) returned (where $current_page is set to the filename of the current page, and gets the total number of hits today from your hit tracking program). You can place and set the value of the $hit_counter variable right inside the brackets of the switch() statement.


As a utility, you could set this function within each page and have it run once each time the page is displayed. The user would immediately see an indication of the number of hits for that page (although some users might be tempted to keep refreshing the page to up the number of hits).

How Values Get Inside Functions

As discussed earlier, parameters are placeholders representing values passed into a function. But there is more than one way to get a value into a parameter so that the function can work on it. You can pass a value into a function by value or by reference. The difference is subtle, but sometimes very important.


When you pass a value into a function by value, you assign the value directly to a parameter. But when you pass a value into a function by reference, you connect the parameter directly to a variable outside the function, forcing the outside variable to adopt whatever value the parameter gets.

Passing Values by Value

All the functions you've seen so far passed values by value. A value is passed into the function by entering the value (literally, or by naming the variable containing the value) into the spot reserved for that value (the place within the parentheses following the function call).
For instance, in the first bonus example, you can pass in the total sales value by entering a number directly into the spot reserved for the argument, or you can simply set a variable equal to total sales and then enter the variable name into that spot. The following code shows both methods of passing by value:


function bonus($total_sales)
{
   $bonus = $total_sales * 0.15;
   return $bonus;
}
$total_sales = 120499;
echo "Your bonus is " . bonus($total_sales);
echo "Your total sales were " . $total_sales;
echo "Your total sales were $120,499 and your bonus is " . bonus(120499);

Notice that even after the value of $total_sales is set outside the function and then passed inside the function for processing, the external value of $total_sales is not changed. No surprises here.

Passing Values by Reference

Passing values into a function by reference has a completely different effect. The external variable used to contain the value being passed into the function is actually changed while the value is being processed. It changes because, in fact, you're not passing a value into the function, you're passing a reference that points directly to the external function. It's as though all processing operations taking place inside the function are actually affecting the external variable directly.


How is it done? Put the ampersand (&) before the name of the argument to be passed by reference. Our next example shows this for the $salary argument.


So suppose you were adding a bonus to a variable called $salary. Obviously you could do that outside the function, but perhaps it would be a little easier and cleaner to do it inside the function. The following code shows how this could work:


function bonus($total_sales,&$salary)
{
   $bonus = $total_sales * 0.15;
   $salary = $salary + $bonus;
   return $salary;
}
$total_sales = 120499;
$salary = 40000;
bonus ($total_sales, $salary);
echo "Your salary, including your bonus is " . $salary;
echo "Your total sales were " . $total_sales;

In this case, you don't need to set any variable to the value resulting from calling the bonus() function; you set $ salary to 40,000, then pass it by reference into the bonus() function, and when the function is done, it passes the value directly back into the $salary variable by reference. Neat, eh!

Setting Default Parameter Values

Like many other programming and computer related things, you can write your functions to have default values. For example, you can define an argument as having a default value, which the parameter for that argument will adopt when the function is called, provided you don't pass a value in for that argument.


But there is one catch: you must define any arguments with default values to the right of any arguments without default values. This is a little odd, but if you don't write your functions that way, they won't work as you'd expect. The following example writes the bonus function with a default value of $40,000 for salary to the right of the argument for total_sales:


function bonus($total_sales, &$salary = 40000)
{
   $bonus = $total_sales * 0.15;
   $salary = $salary + $bonus;
    return $salary;
}
$total_sales = 120499;
bonus($total_sales);
echo "Your salary, including your bonus is " . $salary;
echo "Your total sales were " . $total_sales;

This means that if you supplied no $salary value to the function, it would automatically use 40000 to calculate with. But if you do pass a value (higher, lower, the same—it doesn't matter) to the function for salary, the function would use the passed value to calculate with.

Parameter Order Matters

When you call a PHP function, whether you wrote it or it's built-in, the order in which you pass argument values does matter. If you leave an argument(s) out at the end of the list of arguments, you can leave off the last comma separating arguments. Also, if you leave out an argument, the function will automatically assume a zero value for a numerical argument, or an empty string for a string argument (unless the function defines a default parameter value itself), and continue processing. You'll only get a warning or error message when a required argument (one without any default value set) is missing, but of course, the level of warning or error message you receive will depend on the version of PHP you're using and also possibly on the way you're set error reporting.