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 • FUNCTIONSThis yields the following result:Copyright 2010 W. Jason GilmorePassing Arguments by ValueYou‘ll often find it useful to pass data into a function. As an example, let’s create a function thatcalculates an item’s total cost by determining its sales tax and then adding that amount to the price: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 thecalculation. Although these parameters are intended to be floating points, because of <strong>PHP</strong>’s weak typing,nothing prevents you from passing in variables of any datatype, but the outcome might not be what youexpect. In addition, you’re allowed to define as few or as many parameters as you deem necessary; thereare no language-imposed constraints in this regard.Once defined, you can then invoke the function as demonstrated in the previous section. Forexample, 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 variableslike this:When you pass an argument in this manner, it’s called passing by value. This means that anychanges made to those values within the scope of the function are ignored outside of the function. If youwant these changes to be reflected outside of the function’s scope, you can pass the argument byreference, introduced next.■ Note You don’t necessarily need to define the function before it’s invoked because <strong>PHP</strong> reads the entire scriptinto the engine before execution. Therefore, you could actually call calcSalesTax() before it is defined, althoughsuch haphazard practice is not typical.93

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

Saved successfully!

Ooh no, something went wrong!