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?
a source to share
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.
a source to share
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.
a source to share