views:

425

answers:

3

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?

+2  A: 

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
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
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
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
A: 

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
A: 

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