Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to pass-by-reference in PHP

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); } 
like image 435
Vidar Vestnes Avatar asked Jan 28 '10 20:01

Vidar Vestnes


People also ask

When should passing by reference be used?

Use pass-by-reference if you want to modify the argument value in the calling function. Otherwise, use pass-by-value to pass arguments. The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot.

Should you pass by reference in PHP?

The short answer is use references when you need the functionality that they provide. Don't think of them in terms of memory usage or speed. Pass by reference is always going to be slower if the variable is read only. Everything is passed by value, including objects.

Why do we need call by reference in PHP?

In case of PHP call by reference, actual value is modified if it is modified inside the function. In such case, you need to use & (ampersand) symbol with formal arguments. The & represents reference of the variable.

Is passing by reference faster PHP?

The bigger the array (or the greater the count of calls) the bigger the difference. So in this case, calling by reference is faster because the value is changed inside the function.


1 Answers

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 ;-)

like image 133
Pascal MARTIN Avatar answered Oct 06 '22 01:10

Pascal MARTIN