Prev | Current Page 189 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


?– Note You don??™t necessarily need to define the function before it??™s invoked because PHP reads the
entire script into the engine before execution. Therefore, you could actually call calcSalesTax()
before it is defined, although such haphazard practice is not recommended.
CHAPTER 4 ?–  FUNCTIONS 117
Passing Arguments by Reference
On occasion, you may want any changes made to an argument within a function
to be reflected outside of the function??™s scope. Passing the argument by reference
accomplishes this. Passing an argument by reference is done by appending an ampersand
to the front of the argument. An example follows:
$cost = 20.99;
$tax = 0.0575;
function calculateCost(&$cost, $tax)
{
// Modify the $cost variable
$cost = $cost + ($cost * $tax);
// Perform some random change to the $tax variable.
$tax += 4;
}
calculateCost($cost, $tax);
printf("Tax is %01.2f%%
", $tax*100);
printf("Cost is: $%01.2f", $cost);
?>
Here??™s the result:
Tax is 5.75%
Cost is $22.20
Note the value of $tax remains the same, although $cost has changed.
118 CHAPTER 4 ?–  F UNCT I ONS
Default Argument Values
Default values can be assigned to input arguments, which will be automatically assigned
to the argument if no other value is provided. To revise the sales tax example, suppose
that the majority of your sales are to take place in Franklin County, Ohio.


Pages:
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201