You could
then assign $tax the default value of 6.75 percent, like this:
function calcSalesTax($price, $tax=.0675)
{
$total = $price + ($price * $tax);
echo "Total cost: $total";
}
You can still pass $tax another taxation rate; 6.75 percent will be used only if
calcSalesTax() is invoked, like this:
$price = 15.47;
calcSalesTax($price);
Default argument values must appear at the end of the parameter list and must be
constant expressions; you cannot assign nonconstant values such as function calls or
variables.
You can designate certain arguments as optional by placing them at the end of the
list and assigning them a default value of nothing, like so:
function calcSalesTax($price, $tax="")
{
$total = $price + ($price * $tax);
echo "Total cost: $total";
}
This allows you to call calcSalesTax() without the second parameter if there is no
sales tax:
calcSalesTax(42.00);
This returns the following output:
Total cost: $42.00
CHAPTER 4 ?– FUNCTIONS 119
If multiple optional arguments are specified, you can selectively choose which
ones are passed along. Consider this example:
function calculate($price, $price2="", $price3="")
{
echo $price + $price2 + $price3;
}
You can then call calculate(), passing along just $price and $price3, like so:
calculate(10, "", 3);
This returns the following value:
13
Returning Values from a Function
Often, simply relying on a function to do something is insufficient; a script??™s outcome
might depend on a function??™s outcome, or on changes in data resulting from its execution.
Pages:
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202