pass by reference

When you call a function normally within PHP the variable that you pass is a copy of, for example

function doesNotAlter($alterMe)
{
   $alterMe++;
}
$pleaseAlterMe = 4;
doesNotAlter($pleaseAlterMe);

that will alter the $alterMe variable by adding one to it, but it will only alter it in a local scope of that variable so the actual variable that was passed ($pleaseAlterMe) will not change its value.

But if you pass by reference, then you bring the passing variable into the local scope of that function and thus any alternations to it will act on the variable that has been passed, the only thing that you need to alter is to add a (&), which is very similar to c/c++ which passes the reference to the object (pointer to).

function doesNotAlter(&$alterMe)
{
   $alterMe++;
}
$pleaseAlterMe = 4;
doesNotAlter($pleaseAlterMe);

The & is added to the variable in the passing function parameter list and that is all that it takes to make that remote variable to the function doesNotAlter, to now become a local scoped variable that will alter, so I could change the function name to doesAlter ;).

function doesAlter(&$alterMe)
{
   $alterMe++;
}
$pleaseAlterMe = 4;
doesNotAlter($pleaseAlterMe);
echo $pleaseAlterMe;

So now output would be “5”, because the local variable to the execution of the program is $pleaseAlterMe is first set to 4 and then passed by reference to the doesAlter me function which will actually alter that variable (by adding one to it) and then when you output that variable it will be 5.

Leave a Reply

Your email address will not be published.