PHP Question: Pass By Reference

19th April 2011

Question

Consider the following:

  1. function doSomething(&$val) {
  2. $val++;
  3. }
  4.  
  5. $a = 1;
  6. 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:

  1. function doSomething($val) {
  2. $val++;
  3. }
  4.  
  5. $a = 1;
  6. 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

Permalink

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

Mihai Baboi (Tue, 04/19/2011 - 21:56)

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

Jan (Thu, 09/08/2011 - 18:03)

Add new comment

The content of this field is kept private and will not be shown publicly.