Yet variable scoping prevents information from easily being passed from a function
body back to its caller; so how can we accomplish this? You can pass data back to the
caller by way of the return() statement.
The return Statement
The return() statement returns any ensuing value back to the function caller, returning
program control back to the caller??™s scope in the process. If return() is called from
within the global scope, the script execution is terminated. Revising the calcSalestax()
function again, suppose you don??™t want to immediately echo the sales total back to
the user upon calculation, but rather want to return the value to the calling block:
function calcSalesTax($price, $tax=.0675)
{
$total = $price + ($price * $tax);
return $total;
}
120 CHAPTER 4 ?– F UNCT I ONS
Alternatively, you could return the calculation directly without even assigning it to
$total, like this:
function calcSalesTax($price, $tax=.0675)
{
return $price + ($price * $tax);
}
Here??™s an example of how you would call this function:
$price = 6.99;
$total = calcSalesTax($price);
?>
Returning Multiple Values
It??™s often convenient to return multiple values from a function. For example, suppose
that you??™d like to create a function that retrieves user data from a database, say the
user??™s name, e-mail address, and phone number, and returns it to the caller.
Pages:
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203