Search the Community
Showing results for tags 'chapter10'.
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>Cost Calculator</title> </head> <body> <?php // Script 10.4 - calculator.php /* this script displays and handles an HTML form. It uses a function to calculate a total from a quantity and price. */ //this function returns the calculations function calculate_total ($quantity, $price) { $total = $quantity * $price; //calculation $total = number_format ($total, 2); //formatting return $total; //return the value. } //end of calculate_total() function //check for form submisstion if ($_SERVER['REQUEST_METHOD'] == 'POST') { //form validation if (is_numeric($_POST['quantity']) && is_numeric($_POST['price'])) { //call the function and print the results $total = calculate_total($_POST['quantity'], $_POST['price']); print "<p>Your total comes to $<span style=\"font-weight: bold;\">$total.</span></p>"; } else { print '<p style="color: red;">Please make sure to enter only numbers into the calculator.</p>'; } // end of form validation } // end of if checking form has been submitted. ?> <form action="calculator.php" method="POST"> <p>Quantity: <input type="text" name="quantity" size="3" /></p> <p>Price: <input type="text" name="price" size="3" /></p> <p><input type="submit" name="submit" value="Calculate!" /></p> </body> </html> Are variables located inside of functions separate from variables located outside of functions? For example in the above code, the calculate_total() function returns the variable $total. But later on in the script, I assign $total to this: $total = calculate_total($_POST['quantity'], $_POST['price']); By doing that am I overwriting the $total variable? My guess is that the answer is no, because I tried changing the $total variable to something different, for example to $sum, like this: //call the function and print the results $sum = calculate_total($_POST['quantity'], $_POST['price']); print "<p>Your total comes to $<span style=\"font-weight: bold;\">$sum.</span></p>"; and the function still worked properly. I was just looking for a little clarification on this. Thanks. Tim