What is the purpose of & in PHP?

Asked

Viewed 66 times

3

I have the following code snippet:

$a = '1';
$b = &$a;
$b = "2$b";
echo $a.", ".$b;

Exit:

21, 21

I realized that there is no assignment to the variable $a other than the fact that $b = &$a using the &, that in the end, the result is changed. I did not understand very well, so I question myself:

What does the & for this situation? What would be the goal? And at what point is it used?

  • So that instead of using the value the variable manipulation use as "reference", ie when copying the value to another "variable" it will be possible to manipulate the original variable through the other (more or less this) :)

  • Related: https://answall.com/questions/51209/use_joint-operations-functions-em-php

  • The answers of the colleagues are great, I just suggest to read the documentation of Objects and references PHP, to clarify doubts.

  • 2

    @Wallacemaxters I can barely see your moves.

2 answers

6


The difference between using and not using & is that with & a reference is made, you will be using the same variable in memory, even if the variable name is different, if you change one, change the other and vice versa.

Without & you make a copy of the variable, if you change any of the two, one will not affect the other, are independent and point to different places in memory.

<?php

$a = '1'; // $a = '1'
$b = &$a; // $b = $a = 1
$b = "2$b"; // $b = "2($a)" = "21"
echo $a.", ".$b; // Como $b faz referência a $a e vice versa, $b foi alterado para 21 na linha acima, logo a saída será igual, 21 para ambos os valores

4

The & serves to assign or modify a variable by reference.

$b = &$a

It means every time $a is alerado $b will have the same value as $b always points to $a. If the value $b change $a will have the same value.

How is the interpretation of this code:

$a = '1';
$b = &$a; //ambas as variáveis tem valor 1
$b = "2$b"; // $b recebe o número 2 seguido do seu valor anterior ou seja 1 e modifica/sobrescreve o valor `$a`
echo $a.", ".$b; //

Browser other questions tagged

You are not signed in. Login or sign up in order to post.