0

With PHP5 using "copy on write" and passing by reference causing more of a performance penalty than a gain, why should I use pass-by-reference? Other than call-back functions that would return more than one value or classes who's attributes you want to be alterable without calling a set function later(bad practice, I know), is there a use for it that I am missing?

Charles
  • 48,924
  • 13
  • 96
  • 136
Tyson of the Northwest
  • 1,990
  • 2
  • 18
  • 33

3 Answers3

3

You use pass-by-reference when you want to modify the result and that's all there is to it.

Remember as well that in PHP objects are always pass-by-reference.

Personally I find PHP's system of copying values implicitly (I guess to defend against accidental modification) cumbersome and unintuitive but then again I started in strongly typed languages, which probably explains that. But I find it interesting that objects differ from PHP's normal operation and I take it as evidence that PHP"s implicit copying mechanism really isn't a good system.

cletus
  • 578,732
  • 155
  • 890
  • 933
  • Java's behavior is identical to PHP's (objects passed by reference, primitives passed ["copied"] by value), as is, I believe, C++'s. Which strongly typed languages were you referring to? – Frank Farmer May 20 '09 at 00:36
  • 2
    Java does *not* pass objects by reference; it copies the value of an object reference; see http://stackoverflow.com/questions/40480/is-java-pass-by-reference. – Rob May 20 '09 at 00:48
  • 1
    Fair enough. Based on laurentb's example below, it looks like you could say the same about PHP, which only reinforces my point: the way arguments are passed in PHP and Java are nearly indistinguishable. I'm still waiting for an example of a "strongly typed language" that copies objects passed as arguments outright. – Frank Farmer May 21 '09 at 19:57
  • @FrankFarmer: the thing is, in both Java and PHP 5, objects are not values. When you create a new object, you get an *object reference*. If you look at a language where you can have objects as values and has pass by value, e.g. C++, then when you pass objects it copies them – newacct Dec 25 '12 at 08:10
2

A recursive function that fills an array? Remember writing something like that, once.

There's no point in having hundreds of copies of a partially filled array and copying, splicing and joining parts at every turn.

aib
  • 41,235
  • 10
  • 69
  • 75
0

Even when passing objects there is a difference.

Try this example:

class Penguin { }

$a = new Penguin();

function one($a)
{
  $a = null;
}

function two(&$a)
{
  $a = null;
}

var_dump($a);
one($a);
var_dump($a);
two($a);
var_dump($a);

The result will be:

object(Penguin)#1 (0) {}
object(Penguin)#1 (0) {}
NULL

When you pass a variable containing a reference to an object by reference, you are able to modify the reference to the object.

laurentb
  • 1,065
  • 8
  • 6