Creating and Using Functions that Return a Value

I l @ ve RuBoard

Once you've begun writing functions that take an argument, the next step is to have a function return an output or a value. To do so requires just two more steps. First, you use the return statement within the function. Second, you must assign the output somehow when you call the function. Commonly you would assign the returned value to a variable, but you could also, for example, directly print the output. Here is the basic format for a function that takes an argument and returns a value:

 function FunctionName ($Argument) {    statement(s);    return $Value; } 

Normally this function would be used with a line of code such as:

 $Value = FunctionName($Variable); 

Note that I've assigned the returned value of the function to a variable. To best demonstrate this concept and its various uses, you'll create two functions based upon the numbers .php page started in Chapter 4, Using Numbers , and later modified in Chapter 6, Control Structures .

To create and use a function that returns a value:

  1. Open numbers.php in your text editor (Script 9.5).

    Script 9.5. This is the most recent version of numbers.php, last modified in Chapter 6, Control Structures. You'll modularize the processes in this script by creating two functions.

    graphics/09sc05.gif

  2. Open the initial PHP section and start the first function, CalculateTotal(), that contains lines 14-21 from the original page (Script 9.6):

    Script 9.6. Both functions in this script return a value. When the CalculateTotal function is called, the returned value is assigned to a variable. When the CalculatePayments function is called, the returned value is printed to the browser.

    graphics/09sc06.jpg

     <?php function CalculateTotal ($HowMany,  $Price, $TaxRate, $Savings) {    $TaxRate++; // $TaxRate is now    worth 1.06.    $TheCost = ($Price * $HowMany);    if (($TheCost < 50) AND    ($Savings)) {       print ("Your $$Savings         will not apply because         the total value of the         sale is under !\n<P>");    }    if ($TheCost >= 50) {       $TheCost = $TheCost -         $Savings;    }    $TheCost = $TheCost * $TaxRate;    return $TheCost; } 

    This function takes four argumentsthe number of widgets purchased, the price of each widget, the applicable tax rate, and the discount the customer may havethen makes the necessary calculations to determine the total cost which it returns.

  3. Now create a second function:

     function CalculatePayments  ($Amount, $NumberPayments) {     $Payments = round($Amount, 2) /      $NumberPayments;     $Payments = sprintf ("%01.2f",       $Payments);      return $Payments; } 

    The CalculatePayments() function will take two argumentsa total amount and the number of paymentsand perform a simple calculation. First, the function determines the payment amount using the same formula that numbers.php orginally used. Then, the $Payments value is formatted using the sprintf() function, which, as I said in Chapter 4, Using Numbers , works exactly like printf() only it does not print anything to the browser, it just alters the variable accordingly . Finally, the value of $Payments is returned.

    The benefits of putting even a one-step calculation into a function are twofold: first, it will be easier to find and modify at a later date with your function located at the beginning of your script instead of hidden in the rest of the code; and, second, should you want to repeat the action again in a script, you can do so without duplicating code.

  4. Close the initial PHP section, then create the basic HTML header.

     ?><HTML><HEAD><TITLE>Calculation   Functions</TITLE></HEAD><BODY> 
  5. Open a new PHP section and set your variables :

     <?php $Cost = 20.00; $Tax = 0.06; 

    I've not changed the value of the $Cost variable, but you can set it, as well as $Tax, to whatever value you prefer.

  6. Now write the heart of the PHP script.


    Figure .

    graphics/09sc06a.jpg


     if ($Quantity) {     $Quantity = abs($Quantity);     $Discount = abs($Discount);     $TotalCost = CalculateTotal       ($Quantity, $Cost, $Tax,  $Discount);      // Print the results.      print ("You requested to purchase       $Quantity widget(s) at $$Cost       each.\n<P>");      print ("The total with tax, minus      your $$Discount, comes to $");      printf ("%01.2f", $TotalCost);      print (".\n<P>You may purchase      the widget(s)in 12 monthly      installments of $");      print (CalculatePayments      ($TotalCost, "12"));      print (" each.\n<P>"); }  else {      print ("Please make sure that      you have entered both a      quantity and an applicable      discount and then resubmit.\n"); } 

    Except for the calls to the functions, this section is exactly as it was when you wrote it in Chapter 6, but now you've increased the efficiency of the page by separating out the calculations into their own functions. This section of code also demonstrates the two ways of using functions that return a value. On line 31 a variable is set to the returned value of the CalculateTotal() function and on line 37 the result of calling the CalculatePayment() function is immediately printed.

  7. Close this last PHP section and then finish the HTML.

     ?></BODY></HTML> 
  8. Save your script, upload it to the server, and test it in your Web browser (Figure 9.4). Remember to send the script a Quantity value (and a Discount value, if you want)by appending it to the URL or via an HTML form. If the script does not receive a Quantity value you'll see the "Please make sure " error message generated by line 40.

    Figure 9.4. Again, although the actual results are like those you had without functions, these functions can be universally applied across an entire Web site. Creating functions such as these two as you work also expedites future programming projects by building up a strong library of reusable code.

    graphics/09fig04.gif

Tip

In the CalculatePayments() function you could change the sprintf() line to printf(), immediately printing the result and just remove the return statement altogether. Although I haven't done so here, it's perfectly reasonable to have your function directly print out any results.


Tip

You can only have one return statement executed in a function but the same func-tion can have multiple return statements. As an example, you may want to write a function that checks for a condition and returns whether or not the condition was satisfied. In such a case you would code, in your function:

 if (condition) {    return TRUE; } else {    return FALSE; } 

The result returned by the function then is either TRUE or FALSE indicating whether or not the stated condition was met.


Tip

A return statement can only return one value. In order to return multiple values, you'll need to make use of arrays. See Appendix C, PHP Resources , for more on where you can learn about returning multiple values.


I l @ ve RuBoard


PHP for the World Wide Web (Visual QuickStart Guide)
PHP for the World Wide Web (Visual QuickStart Guide)
ISBN: 0201727870
EAN: 2147483647
Year: 2001
Pages: 116
Authors: Larry Ullman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net