• Aucun résultat trouvé

Returning values from a function

Dans le document PHP 6 (Page 122-127)

The final attribute of a user-defined func-tion to discuss is that of returning values.

Some, but not all, functions do this. For example,print()will return either a 1or a0indicating its success, whereas echo()

will not. As another example, the strlen()

function returns a number correlating to the number of characters in a string.

To have a function return a value, use the

returnstatement.

function find_sign ($month, $day) { // Function code.

return $sign;

}

A function can return a value (say a string or a number) or a variable whose value has been created by the function. When calling a function that returns a value, you can assign the function result to a variable:

$my_sign = find_sign (‘October’, 23);

or use it as an argument when calling anoth-er function:

print find_sign (‘October’, 23);

Let’s update the calculate_total()function one last time so that it returns the calculat-ed total instead of printing it.

Creating Dynamic Web Sites

Crea ting Y our Own F unctions

Figure3.17If the user enters a tax value, it will be used instead of the default value.

Figure3.18The PHP manual’s description of the number_format()function shows that only the first argument is required.

continues on next page

To have a function return a value:

1. Open calculator.php(refer to Script 3.9) in your text editor or IDE.

2. Remove the echo()statement from the function definition and replace it with a

returnstatement (Script 3.10)

return number_format($total, 2);

This version of the function will not print the results. Instead it will return just the calculated total, formatted to two decimal places.

3. Change the function call lines to

if (is_numeric($_POST[‘tax’])) {

$sum = calculate_total ($_POST

[‘quantity’], $_POST[‘price’],

$_POST[‘tax’]);

} else {

$sum = calculate_total ($_POST

[‘quantity’], $_POST[‘price’]);

}

Since the function now returns instead of prints the calculation results, the invo-cation of the function needs to be assigned to a variable so that the total can be printed later in the script.

Crea ting Y our Own F unctions

1 <?php # Script 3.10 - calculator.php #5 2

3 $page_title = ‘Widget Cost Calculator’;

4 include (‘includes/header.html’);

5

6 /* This function calculates a total 7 and then returns the results.

8 The $tax argument is optional (it has a default value). */

9 function calculate_total ($qty, $cost,

$tax = 5) {

15 return number_format($total, 2);

16

17 } // End of function.

18

19 // Check for form submission:

20 if (isset($_POST[‘submitted’])) { 21

22 // Minimal form validation:

23 if ( is_numeric($_POST[‘quantity’]) &&

is_numeric($_POST[‘price’]) ) { 24

25 // Print the heading:

26 echo ‘<h1>Total Cost</h1>’;

27

28 // Call the function, with or without tax:

29 if (is_numeric($_POST[‘tax’])) {

Script3.10The calculate_total()function now performs the calculations and returns the calculated result.

(script continues on next page) continues on page 104

Creating Dynamic Web Sites

Crea ting Y our Own F unctions

Script3.10continued

30 $sum = calculate_total ($_POST[‘quantity’], $_POST[‘price’], $_POST[‘tax’]);

31 } else {

32 $sum = calculate_total ($_POST[‘quantity’], $_POST[‘price’]);

33 }

34

35 // Print the results:

36 echo ‘<p>The total cost of purchasing ‘ . $_POST[‘quantity’] . ‘ widget(s) at $’ . number_

format ($_POST[‘price’], 2) . ‘ each, with tax, is $’ . $sum . ‘.</p>’;

37

38 } else { // Invalid submitted values.

39 echo ‘<h1>Error!</h1>

40 <p class=”error”>Please enter a valid quantity and price.</p>’;

41 }

42

43 } // End of main isset() IF.

44

45 // Leave the PHP section and create the HTML form:

46 ?>

47 <h1>Widget Cost Calculator</h1>

48 <form action=”calculator.php” method=”post”>

49 <p>Quantity: <input type=”text” name=”quantity” size=”5” maxlength=”5” value=”<?php if (isset($_POST[‘quantity’])) echo $_POST[‘quantity’]; ?>” /></p>

50 <p>Price: <input type=”text” name=”price” size=”5” maxlength=”10” value=”<?php if (isset($_POST[‘price’])) echo $_POST[‘price’]; ?>” /></p>

51 <p>Tax (%): <input type=”text” name=”tax” size=”5” maxlength=”5” value=”<?php if (isset($_POST[‘tax’])) echo $_POST[‘tax’]; ?>” /> (optional)</p>

52 <p><input type=”submit” name=”submit” value=”Calculate!” /></p>

53 <input type=”hidden” name=”submitted” value=”TRUE” />

54 </form>

55 <?php // Include the footer:

56 include (‘includes/footer.html’);

57 ?>

4. Add a new echo()statement that prints the results.

echo ‘<p>The total cost of

purchasing ‘ . $_POST[‘quantity’]

. ‘ widget(s) at $’ . number_

format ($_POST[‘price’], 2) . ‘

each, with tax, is $’ . $sum .

‘.</p>’;

Since the function just returns a value, a new echo()statement must be added to the main code. This statement uses the quantity and price from the form (both found in $_POST) and the total returned by the function (assigned to $sum). It does not, however, report on the tax rate used (see the final tip).

5. Save the file, place it in your Web direc-tory, and test it in your Web browser (Figure 3.19).

Tips

Although this last example may seem more complex (with the function per-forming a calculation and the main code printing the results), it actually demon-strates better programming style. Ideally, functions should perform universal, obvi-ous tasks (like a calculation) and be independent of page-specific factors like HTML formatting.

Thereturnstatement terminates the code execution at that point, so any code within a function after an executed

returnwill never run.

Crea ting Y our Own F unctions

Figure3.19The calculator’s user-defined function now returns, instead of prints, the results, but this change has little impact on what the user sees.

A function can have multiple return

statements (e.g., in a switchstatement or conditional) but only one, at most, will ever be invoked. For example, functions commonly do something like this:

function some_function () { if (/* condition */) { return TRUE;

} else {

return FALSE;

} }

To have a function return multiple val-ues, use the array()function to return an array. By changing the return line in Script 3.10 to

return array ($total, $tax);

the function could return both the total of the calculation and the tax rate used (which could be the default value or a user-supplied one).

When calling a function that returns an array, use the list()function to assign the array elements to individual vari-ables:

list ($sum, $taxrate) = calculate_

total ($_POST[‘quantity’],

$_POST[‘price’], $_POST[‘tax’]);

Creating Dynamic Web Sites

Crea ting Y our Own F unctions

Crea ting Y our Own F unctions

Dans le document PHP 6 (Page 122-127)