11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 4 • FUNCTIONSwww.it-ebooks.infoPassing Arguments by ReferenceOn occasion, you may want any changes made to an argument within a function to be reflected outsideof the function’s scope. Passing the argument by reference accomplishes this. Passing an argument byreference is done by appending an ampersand to the front of the argument. Here’s an example:$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.20Note the value of $tax remains the same, although $cost has changed.Default Argument ValuesDefault values can be assigned to input arguments, which will be automatically assigned to theargument if no other value is provided. To revise the sales tax example, suppose that the majority of yoursales take place in Franklin County, Ohio. 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() isinvoked without the second parameter like this:94

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!