Thursday, April 4, 2013

PHP Functions -> variable

What is difference between call by value and call by reference in function.


When we pass an argument to a function, by default all are call by value. It means if we do the changes with that variable, It will not reflect the variable value. See example Below.

function inc_callbyvalue($testValue) {
    $testValue++;
}
$testValue = 1;
inc_callbyvalue($testValue);
echo $testValue;

In above example, $testValue will return 1 although we have increased in function. Because we have use call by value.


If we pass an argument by call by reference, It will reflect the changes whatever we have done with that.
function inc_callByRef(&$testValue) {
    $testValue++;
}
$testValue = 1;
inc_callByRef($testValue);
echo $testValue;


In above example, $testValue will return 2, because we have use call by reference.

No comments:

Post a Comment