Do I need to pass a variable by reference in php5?

With PHP5 using "copy on write" and passing by reference causing more performance penalty than gain, why should I use pass-by-reference? Apart from callback functions that return more than one value or classes which are the attributes you want to change without calling the set function later (bad practice, I know), is there a use for this that I am missing?

0


a source to share


3 answers


You use pass-by-reference when you want to change the result and whatever it needs.

Remember also that PHP objects are always passed by reference.



Personally, I find the PHP system for copying values ​​implicitly (I think to protect against accidental modification) cumbersome and unintuitive, but then I started with strongly typed languages, which probably explains this. But I'm curious that objects are different from how PHP works, and I take this as proof that PHP's implicit copy mechanism is not a good system.

+3


a source


Recursive function that populates an array? Remember that you once wrote something like this.



It doesn't make sense to have hundreds of copies of a partially filled pattern and copy, splicing and joining parts every step of the way.

+2


a source


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 can change the reference to the object.

0


a source







All Articles