Please excuse me if this blog post is not up to my normal quality. I am writing another blog post on something I have been working on, but in order for readers to fully appreciate it I needed to explain some other things first. This specific blog post is about three levels deep in this pattern.

So, what is a pass-by-reference variable and how is it different than a more traditional one?

You can read all about PHP references on the official PHP page about it, but I will do my best to explain it in my own words here.

Say you have the following:

<?php

$a = 'foo';
$b = $a;
$b .= 'bar';

echo $a; // foo
echo $b; // foobar

Everything seems to make sense so far. $b was set to what $a was, then we appended bar to it. $a remained at foo and $b became foobar.

How would references work? Well consider the following:

<?php

$a = 'foo';
$b =& $a;
$b .= 'bar';

echo $a; // foobar
echo $b; // foobar

Wait, hold up, what just happened? The code is the exact same except for one little &. What gives? Well that, in short, is a pass by reference situation. The explination for this is pretty simple. We set the value of $a, we set $b to equal to the memory reference of $a, then appended bar to $b. What this means is that since both $a and $b point to the same location in memory, whenever you change one the other is also updated. Thus, when we appended bar to one of the variables both reflect the change.

So can you use this anywhere else? In functions, perhaps? Sure you can! Look at this example:

<?php

function incrementInput(int &$num): void
{
    $num++;
}

$myInteger = 0;

incrementInput($myInteger);
echo $myInteger; // 1

incrementInput($myInteger);
echo $myInteger; // 2

Notice in this case that the function being called did not return anything. Its return type is literally void. It is incrementing the variable we pass into it though.

So thats about it. Once you understand how this works you will see it everywhere (some array_* functions, for example). I hope someone finds this useful!