As an example, let??™s create
a function that calculates an item??™s total cost by determining its sales tax and then
adding that amount to the price:
116 CHAPTER 4 ?– F UNCT I ONS
function calcSalesTax($price, $tax)
{
$total = $price + ($price * $tax);
echo "Total cost: $total";
}
This function accepts two parameters, aptly named $price and $tax, which are
used in the calculation. Although these parameters are intended to be floating points,
because of PHP??™s weak typing, nothing prevents you from passing in variables of any
datatype, but the outcome might not be what you expect. In addition, you??™re allowed
to define as few or as many parameters as you deem necessary; there are no languageimposed
constraints in this regard.
Once defined, you can then invoke the function as demonstrated in the previous
section. For example, the calcSalesTax() function would be called like so:
calcSalesTax(15.00, .075);
Of course, you??™re not bound to passing static values into the function. You can also
pass variables like this:
$pricetag = 15.00;
$salestax = .075;
calcSalesTax($pricetag, $salestax);
?>
When you pass an argument in this manner, it??™s called passing by value. This means
that any changes made to those values within the scope of the function are ignored
outside of the function. If you want these changes to be reflected outside of the function??™s
scope, you can pass the argument by reference, introduced next.
Pages:
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200