PHP Call: Value & Reference


Call by Value

When a function is called by value, a copy of the original argument is passed to the called function. The copied argument occupy separate memory location than the actual argument.

If any changes were done to values inside the function, it is only visible inside the function. Their values remain unchanged outside it.


Example

<?php
// Function definition
function sum($num1, $num2) {
    $sum = $num1 + $num2;
    return $sum;
}

// Main code
$a = 100;
$b = 12;
$result = sum($a, $b);  // call by value

echo "Sum of two numbers value is : " . $result . "\n";
?> 

Call by Reference

The address of argument is copied instead of value. Within the function, the address of argument is used to access the actual argument. If any changes are done inside the function to values, it is visible both inside and outside the function.


Example

<?php
function sum(&$num1, &$num2) {
    $sum = $num1 + $num2;
    echo "Sum of two numbers value is : " . $sum . "\n";
}

$a = 100;
$b = 12;
sum($a, $b);  // call by reference
?>



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.