PHP Question: Pass By Reference

Question

Consider the following:

function doSomething(&$val) {
    $val++;
}

$a = 1;
doSomething($a);

What does the variable $a now equal?









 

Answer

The answer here is '2' because the variable $a was passed by reference to the doSomething() function. Passing a variable by reference means that you don't pass the value of the variable as you normally would, you pass the variable itself (or at least a reference to it). So anything that happens to that variable inside the function effects the variable outside as they point to the same place.

Mihai in the comments asked if using the & character was deprecated in PHP 5.3 and the answer is that it is in certain circumstances. The above function call is fine as the function declaration itself contains the pass by reference definition. What has been deprecated in PHP 5.3 is doing the above example in the opposite way by passing the variable as a reference, like this:

function doSomething($val) {
    $val++;
}

$a = 1;
doSomething(&$a);

This still produces the same result as the original function, but it will also throw a deprecated 'call-time pass-by-reference' notice like the following.

Deprecated: Call-time pass-by-reference has been deprecated in something.php on line x

As a result you should definately get out of the habit of call-time passing by reference in your code, but I don't see normal pass by reference going anywhere as it is quite useful.

Comments

Isn't the use of & deprecated since PHP 5?  Why would you want to use it?

Permalink

The use of & isn´t deprecated since PHP 5, it´s simply not necessary in most cases as objects are always passed by reference. In case your variable doesn´t contain an object, the above example is still correct.

Greats from Germany
Jan

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.