Searching...
Thursday 27 June 2013

Functions in php – Part 2


Passing Arguments by Value

You‘ll often find it useful to pass data into a function. 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:

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 language-imposed constraints in this regard.

Once defined, you can then invoke the function as demonstrated in the Functions in php - Part 1. 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:

<?php
$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 because not the actual value but a copy of the value is passed into the function and when the fucntion ends this value is destroyed. Hence, there is no change to the actual value.

Take this example for instance:-

<?php
$num1= 10
$num2= 20
function something($num1,$num2)
{
    $num1 += $num2;
    echo "$num1";
}
something($num1,$num2);
echo "$num1";
?>

Output:
30
10

If you want these changes to be reflected outside of the function’s scope, you can pass the argument by reference, introduced next.

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, because in this case a copy of the argument is not provided to function instead the argument itself is provided. Hence any change to the argument inside the function will be reflected outside of the function. Passing an argument by reference is done by appending an ampersand(&) to the front of the argument. Here’s an example:

<?php
$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.

Take this another example:-

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
http://letusdophp.blogspot.in/2013/06/functions-in-php-part-2.html $str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

Ques. : Absent any actual need for choosing one method over the other, does passing arrays by value to a read-only function reduce performance compared to passing them by reference?
Ans. : "A copy of the original $array is created within the function scope. Once the function terminates, the scope is removed and the copy of $array with it.

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 for majority of your sales $tax is 6.75 percent :-

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() is invoked without the second parameter like this:

$price = 15.47;
calcSalesTax($price);

Default argument values must appear at the end of the parameter list and must be constant expressions; you cannot assign non-constant values such as function calls or variables.
You can designate certain arguments as optional by placing them at the end of the list and assigning them 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: $42

Now 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:
13

Note again that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.


0 comments:

Post a Comment

 
Back to top!