Jump to content
Larry Ullman's Book Forums

Chapter 3 - Returning Values From A Function


Recommended Posts

Hi there. Completely new to php, working my way through the book. Whilst I got this script to work (Script 3.10), I don't quite understand why it works/worked.

 

In the calculate_trip_cost function, I don't understand how it gets values for the $miles, $mpg and $ppg arguments. They are only defined within the function (which I think might have something to do with Variable Scope, mentioned a couple of pages later), and don't appear to be getting data from the form.

 

If somebody could take the time to explain this to me, I'd be hugely appreciative. Thanks in advance!

Link to comment
Share on other sites

When you call the calculate_trip_cost function (as is the case on line 48 in the script), the three arguments specified within the parentheses and separated by commas are mapped to the three parameters (also sometimes called arguments; it doesn't really matter) within the parentheses in the function definition header on line 24.

 

In the code in the book, this corresponds to the value in $_POST['distance'] being mapped to the parameter $miles, the value in $_POST['efficiency'] being mapped to $mpg, and the value in $_POST['gallon_price'] being mapped to $ppg. (And when I say mapped, I simply mean that the values in the arguments in the function call are copied to the corresponding parameters in the function definition header.) By doing this, you can use values that were set or established outside of the function within the function, which relates to the variable scope discussion.

 

As another example, if I wrote the function call calculate_trip_cost(1, 2, 3), then 1 would be set for $miles, 2 would be set for $mpg, and 3 would be set for $ppg.

 

As for how the $_POST array contains values in the first place, that relates to other discussions earlier in the book. Basically though, when you submit an HTML form (with the post method), PHP is designed to automatically store all values within the form into the $_POST superglobal associative array (just to throw some other vocab out there for you).

 

Does all that make sense? Please let me know if it doesn't.

  • Upvote 3
Link to comment
Share on other sites

Yes, I believe I get it now. I see now how calculate_trip_cost on line 48 maps distance, efficiency and gallon_price to $miles, $mpg and $ppg, respectively.

 

The break down was very much appreciated, thanks!

Link to comment
Share on other sites

 Share

×
×
  • Create New...