Sugandh Khanna
Sugandh Khanna

Reputation: 176

Why isn't this example of call by reference not working?

I am clearing the concept of call-by-reference.Can anyone please explain the code lines below shown as an example of call-by-reference?

 <?php
    function test(){
        $result = 10;
        return $result;
    }
    function reference_test(&$result){
        return $result;
    }
    reference_test($result);
 ?>

Upvotes: 1

Views: 82

Answers (1)

TeeDeJee
TeeDeJee

Reputation: 3741

You have two problems.

  1. $result is never set and the test function is never called.
  2. You do a pass by reference on the wrong function. A pass by reference is to change the variable inside and outside the function.

Here is the solution, changed the function a bit to show you the difference. You don't need to return the variable you changed by reference.

// Pass by ref: because you want the value of $result to change in your normal code.
// $nochange is pass by value so it will only change inside the function.
function test(&$result, $nochange){ 
    $result = 10;
    $nochange = 10;
}
// Just returns result
function reference_test($result){ 
    return $result;
}

$result = 0; // Set value to 0
$nochange = 0;
test($result, $nochange); // $result will be 10 because you pass it by reference in this function
// $nochange wont have changed because you pass it by value.
echo reference_test($result); // echo's 10
echo reference_test($nochange); // echo's 0

Upvotes: 1

Related Questions