Hi DW.

Today just came across with something I didn't know of and it may be easy to someone else who had workded with it or had came across it. Look at this example code snippet:

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

This will give you 21, 21 and I didn't see this coming till I looked close to the code and this is caused by line2 which is trigged by &. Now as you can see $a is declared and assigned on line one and it was referenced once in line 2. My question may be stupid but just want to know what & is doing as its also append the 2. If you look very close to the code to these lines: 2 as well as 3, I'm a bit lost.

In line 3 $b = "2$b"; where as in line 2 $b = &$a; which $a = 1; now this 2$b is a bit confusing me as to how it knows 2 and why it doesn't return 221 because what I see is that in line 3 $b = "2{21}"; {} represent the value of line 2.

Anyone who can help me understand whats going on here, I think I see whats happening but can't explain as of answering the question to this. Line 3 is what brings this whole confusion in connection with line 2.

Edited by Mr.M

1 Week
Discussion Span
Last Post by JamesCherrill

The php experts seem to be stil in bed, so I'll have a go...

The & defines a reference. References in PHP are a means to access the same variable content by different names. Its like creating an alias for a file (or more like a Unix hardlink) http://php.net/manual/en/language.references.php

$b = &$a; makes $b an alias for $a

$b = "2$b"; evaluates the literal 2 followed by the value of $b, which is the same value as $a, which is 1, so it evaluates to 21.
$b is updated with that new value.
$b is an alias for $a, so $a is also now 21

echo $a. ", " .$b ; -> 21,21 simples!

Edited by JamesCherrill

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.