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.

www.it-ebooks.infoCHAPTER 4 • FUNCTIONS$price = 15.47;calcSalesTax($price);Default argument values must appear at the end of the parameter list and must be constantexpressions; 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 assigningthem 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: $42If multiple optional arguments are specified, you can selectively choose which ones are passedalong. 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:13Using Type Hinting<strong>PHP</strong> 5 introduced a new feature known as type hinting, which gives you the ability to force parameters tobe objects of a certain class or to be arrays. Unfortunately, type hinting using scalar data types such asintegers and strings is not supported. If the provided parameter is not of the desired type, a fatal errorwill occur. As an example, suppose you created a class named Customer and wanted to be certain thatany parameter passed to a function named processPayPalPayment() was of type Customer. You could usetype hinting to implement this restriction:95

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

Saved successfully!

Ooh no, something went wrong!