The passage for reference I believe to be one of the coolest things in programming.
I think one of the questions to ask when studying this is:
Memory
Imagine that when you are programming and assigning a variable: $var = 5;
,
you are not simply assigning 5 to a $var
variable, you are reserving a location
in the memory of your computer that will have as alias
the name $var
and it local will have
the value 5.
0050 | 0051 | 0052 | 0053 | 0054 | 0055 | 0056 <-- possição da memoria
| | $var | | | | <-- alias
| | 5 | | | | <-- valor/referencia
The alias is actually just an access to the contents of 0052
of memory.
When you generate a passage by reference you are saying that the content of that
memory is not a value, but a reference to a location that has the value.
It's kind of complicated, but it's basically like this:
$b = &$var;
0050 | 0051 | 0052 | 0053 | 0054 | 0055 | 0056 <-- possição da memoria
| | $var | | $b | | <-- alias
| | 5 | | 0052 | | <-- valor/referencia
Now when you access $b
eĺe it will not display 0052
because it is a reference,
it goes to the reference and gets its value in the 5
case.
In this way if the content of the 0052
setting is changed both $var
and $b
will be changed
changed. Remember that you can change it both by $var
and $b
.
$var = 7;
0050 | 0051 | 0052 | 0053 | 0054 | 0055 | 0056 <-- possição da memoria
| | $var | | $b | | <-- alias
| | 7 | | 0052 | | <-- valor/referencia
$b = 10;
0050 | 0051 | 0052 | 0053 | 0054 | 0055 | 0056 <-- possição da memoria
| | $var | | $b | | <-- alias
| | 10 | | 0052 | | <-- valor/referencia
Function
When you generate a function, the variables you create as a parameter generate an
in memory, if they are not of the reference type, they wait to receive a value, if
are of the reference type get the reference of the passed variable.
function teste($a){
}
0080 | 0081 | 0082 | 0083 | 0084 | 0085 | 0086 <-- possição da memoria
| | $a | | | | <-- alias
| | | | | | <-- valor/referencia
teste($var);
0080 | 0081 | 0082 | 0083 | 0084 | 0085 | 0086 <-- possição da memoria
| | $a | | | | <-- alias
| | 5 | | | | <-- valor/referencia
function teste(&$a){
}
0080 | 0081 | 0082 | 0083 | 0084 | 0085 | 0086 <-- possição da memoria
| | $a | | | | <-- alias
| | | | | | <-- valor/referencia
teste($var);
0080 | 0081 | 0082 | 0083 | 0084 | 0085 | 0086 <-- possição da memoria
| | $a | | | | <-- alias
| | 0052 | | | | <-- valor/referencia
Thus $a
within the function changes the location of memory 0052
, changing the content definitively.