Frage

Ok, I know what passing by reference is... I don't need that explained.

Say you have a function that takes in an argument by reference:

function foo(&$a){
   $a = 1;
}

and you call it:

$a = 0;
foo($a); // Now $a is 1.

You can do the same exact thing passing by value:

function foo($a){
   $a = 1;
   return $a;
}

and you call it:

$a = 0;
$a = foo($a);  // Now $a is 1.

So, what is the point of passing by reference?

War es hilfreich?

Lösung

To answer my own question from comments posted above and some other research:

  1. Since only a reference to an object is passed to a function in pass-by-reference, it can be particularly useful when trying to conserve memory.
  2. If there is such a case where you would want to alter an entity but return a different one, pass-by-reference can come in handy (although I would rather use multiple functions with return values).

Other than the two cases, I think this approach can cause confusion in large code bases and result in some nasty code.

If you know of any other reasons that I should add please comment and I'll add them here.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top