Alex Rivera | Logout

When to pass-by-reference in PHP

Asked 2010-01-28T20:42:43.110
37

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);
}
Edit
Report

1 Answer

15

PHP makes use of copy-on-write as much as possible (whenever it would typically increase performance) so using references is not going to give you any performance benefit; it will only hurt. Use references only when you really need them. From the PHP Manual:

Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so.

answered 2010-01-28T21:06:38.757

Your Answer