When to pass-by-reference in PHP

Vidar Vestnes picture Vidar Vestnes · Jan 28, 2010 · Viewed 25.4k times · Source

Im wondering if its good practice to pass-by-reference when you are only reading a variable, or if it should always be passed as a value.

Example with pass-by-reference:

$a = 'fish and chips';
$b = do_my_hash($a);
echo $b;

function &do_my_hash(&$value){
   return md5($value);
}

Example with pass-by-value:

$a = 'fish and chips';
$b = do_my_hash($a);
echo $b;

function do_my_hash($value){
   return md5($value);
}

Which is better ? E.g if I was to run a loop with 1000 rounds ?

Example of loop:

for($i = 0 ; $i < 1000 ; $i++){
   $a = 'Fish & Chips '.$i;
   echo do_my_hash($a);
}

Answer

Pascal MARTIN picture Pascal MARTIN · Jan 28, 2010

If you mean to pass a value (so the function doesn't modify it), there is no reason to pass it by reference : it will only make your code harder to understand, as people will think "this function could modify what I will pass to it — oh, it doesn't modify it?"

In the example you provided, your do_my_hash function doesn't modify the value you're passing to it; so, I wouldn't use a reference.

And if you're concerned about performance, you should read this recent blog post: Do not use PHP references:

Another reason people use reference is since they think it makes the code faster. But this is wrong. It is even worse: References mostly make the code slower! Yes, references often make the code slower - Sorry, I just had to repeat this to make it clear.

Actually, this article might be an interesting read, even if you're not primarily concerned about performance ;-)