Paul Posted April 14, 2011 Share Posted April 14, 2011 Hiya, Referring to script 3.10 it appears that a function needs to be either returned or printed. I'm struggling to understand why that is. In the above mentioned script the function calculate_total performs the calculation of the total and puts it in a variable called $total. Further down the script the function is called based on the values entered on the form and the result placed in a variable called $sum. Now, from the 'Variable Scope' article at the end of the chapter a defined variable within a function cannot be accessed outside it. This, I assume, is why the results of the calculation are put into $sum and not $total. However why does the function need to have the line - return number_format ($total, 2) ? In my mind the function defines the job, this job is then called further down the script and it's results stored in $sum. Why is the return line needed? Thanks Paul Link to comment Share on other sites More sharing options...
Jonathon Posted April 14, 2011 Share Posted April 14, 2011 Hi Paul, I havent looked at the script but the your passing the variables into that function from the form. (from memory). The function tidies up the code and calculations and the number_format formats the the answer to a 2 decimal place because it's meant to return the answer as a monetary value i.e. $4.67, not $4.675636224...., various calculations will rarely return a figure exactly in 2 decimal format hence the use of this function. 1 Link to comment Share on other sites More sharing options...
Larry Posted April 15, 2011 Share Posted April 15, 2011 Hello Paul, You need to get the value out of the function somehow. A function is a "black box": the code outside of the script can't see into it. So the function's return line is how the function returns a value. When the function is called, the returned value is assigned to $sum. Does that answer your question? Link to comment Share on other sites More sharing options...
Recommended Posts