Jump to content
Larry Ullman's Book Forums

Confused About User Defined Functions


Recommended Posts

Hello,

 

I'm pasting a php file below that is one of the exercises in PHP and MYSQL for Dynamic Web Sites. I'm referring to chapter 3, page 105 where Larry discusses returning values from a function.

 

Here is my question in a nutshell.  When defining the function calculate_trip_cost three variable are set $miles, $mpg and $ppg.  I don't understand how these variables work, where do the values come from?  They aren't referred to again in the script.  Could someone, bearing in mind that I'm new at this, explain it a little? 

 

Any help would be so appreciated.  I hate to move on without understanding it completely.

 

Thanks in advance, Steve.

 

The php is below:

 

<?php #Script 3.5 - calculator.php

// This fucntion creates a radio button.
// The function takes two arguments: the value and the name
// The function alos makes the button "sticky".
function create_radio($value, $name = 'gallon_price') {
    
// Start the element:
echo '<input type="radio" name="' .$name.'" value="' .$value.'"';
//Check for stickiness
if (isset($_POST[$name]) && ($_POST[$name] == $value)) {
    echo 'checked="checked"';
}
    echo "/> $value";
}

//End of create_radio()function

//This function calculates the cost of the trip.
//The funcion takes three arguments: the distance, the fuel efficiency and the price per gallon
//The function returns the total cost.

function calculate_trip_cost($miles, $mpg, $ppg) {
    // Get the number of gallons:
    $gallons = $miles/$mpg;
    
    // Get the cost of these gallons
    $dollars = $gallons/$ppg;
    
    //Return the formatted cost:
    return number_format($dollars, 2);
}   // End of calculate_trip_cost() function.

$page_title = 'Trip Cost Calculator';
include ('includes/header.html');

// Check for form submission

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

// Minimal Form Validation

if (isset ($_POST['distance'], $_POST['gallon_price'], $_POST['efficiency']) &&
is_numeric($_POST['distance']) && is_numeric($_POST['gallon_price']) && is_numeric($_POST['efficiency'] ) ) {

// Calculate the results

$cost = calculate_trip_cost ($_POST['distance'], $_POST['efficiency'], $_POST['gallon_price']);
$hours = $_POST['distance'] / 65;

// Print the results

echo '<h1> Total Estimated Costs </h1>
<p>The total cost of driving '.$_POST['distance'].' miles, averaging' .$_POST['efficiency'] .' miles per gallon, and paying an average of $'.$_POST['gallon_price'].' per gallon, is $ '.$cost. '.If you drive at an average of 65 miles per hour, the trip will take approximately ' . number_format($hours, 2) . ' hours.</p>';

} else {//Invalid submitted values.
echo '<h1>Error!</h1>
<p class="error">Please enter a valid distance, price per gallon and fuel efficiency.</p>';
}
} // End of main submission IF.
?>

<h1>Trip Cost Calculator</h1>
<form action="calculator.php" method="post">
<p>Distance (in miles):
<input type="text" name="distance" value="<?php if (isset($_POST['distance'])) echo $_POST['distance'];?>"/></p>

<p>Ave. Price Per Gallon: <span class="input">
<?php
create_radio('3.00');
create_radio('3.50');
create_radio('4.00');
?>



</span></p>

<p> Fuel Efficiency: <select name="efficiency">
<option value="10" <?php if (isset ($_POST['efficiency']) && ($_POST['efficiency'] == '10'))
echo 'selected="selected"';?>>Terrible</option>
<option value="20"<?php if (isset ($_POST['efficiency']) && ($_POST['efficiency'] == '20'))
echo 'selected="selected"';?>>Decent</option>
<option value="30"<?php if (isset ($_POST['efficiency']) && ($_POST['efficiency'] == '30'))
echo 'selected="selected"';?>>Very Good</option>
<option value="50"<?php if (isset ($_POST['efficiency']) && ($_POST['efficiency'] == '50'))
echo 'selected="selected"';?>>Outstanding</option>
</select></p>

<p><input type="submit" value="Calculate!" /></p>
</form>

<?php include ("includes/footer.html"); ?>
 

Link to comment
Share on other sites

Hello and welcome to the forums, Steve.

 

You asked a good question.

Basically, the arguments you pass to the function call are what get assigned to the parameters in the function definition header.

 

More specifically, if you look at line 48 on page 106, you'll see the following:

$cost = calculate_trip_cost($_POST['distance'], $_POST['efficiency'], $_POST['gallon_price']);

That is where the calculate_trip_cost function is actually called.

When you call the function there, the value of $_POST['distance'] is assigned to the $miles parameter on line 24, the $_POST['efficiency'] value is assigned to $mpg and $_POST['gallon_price'] is assigned to $ppg.

 

Does that make sense?

Link to comment
Share on other sites

Hey. So those are variables local to the function itself. They're like the variables used elsewhere in the script, outside of the function, in that they can be completely made up by you. The number of variables, the names, all that is of your creation. But these variables only exist within the function. 

 

These particular variables are also function parameters, which means they can be used to pass values to the function. The values are passed when the function is called. So if I have:

function test($x) { }
test('cat');
test(23);

In the first function call, $x is assigned the value "cat". In the second, $x is assigned the number 23. It's that simple. 

 

Or to use a metaphor, imagine you have a box with 2 holes in the top. Under each hole is a bucket. Those holes are parameters: places you can put something into the box. The buckets are variables that will catch whatever was dropped in that hole. The number of holes and the names given to them (to mix the metaphor) are entirely up to you.

 

Let me know if this is still unclear. 

 

Link to comment
Share on other sites

Thanks so much guys, I really appreciate it.

I'm assuming that the paramaters in the function call are passed in the same order?

In other words:

$cost = calculate_trip_cost($_POST['distance'], $_POST['efficiency'], $_POST['gallon_price']);

is passed to the defined $miles, $mpg, $ppg in the same order?

Link to comment
Share on other sites

 Share

×
×
  • Create New...