Reputation: 5676
I found this awfully old comment in the PHP docs comments, but can't get my mind around it why it outputs "hihaha" and not "eita" in the first example. $a
is changed and I'd assume that "hihaha"
is removed for good. If not, then why is it so that if the change is to null
or assigning a copy of another variable, then the "hihaha"
IS removed for good?
// 1. example
$a = "hihaha";
$b = &$a;
$c = "eita";
$a = &$c; // why doesn't this purge "hihaha" from existence?
echo $b; // shows "hihaha" WHY?
// 2. example
$a = "hihaha";
$b = &$a;
$a = null;
echo $b; // shows nothing (both are set to null)
// 3. example
$a = "hihaha";
$b = &$a;
$c = "eita";
$a = $c;
echo $b; // shows "eita"
Is this a "good way" towards the circular references problem?
Upvotes: 1
Views: 35
Reputation: 41820
Starting with $a = "hihaha";
, when you do $b = &$a;
, $b
is not referencing $a
. It is referencing the content of $a
. As it says in PHP: What References Do:
$a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.
Then after $c = "eita";
, when you do $a = &$c;
, $a
is now referencing the content of $c
("eita").
This does not affect $b
at all. $b
is still referencing the original content of $a
("hihaha"). Pointing $a
at something else does not change that.
In case you have a more mspaint learning style, here is a visual aid representing the first four statements of example 1:
In the second example, $a
and $b
are still pointing at the same content when $a
is set to null
, so $b
is now referencing null
as well. Visually:
Upvotes: 2
Reputation: 1963
Think of a variable as pointing to a reference - to break down Example 1...
1
$a = "hihaha";
$a
points to the reference for the string hihaha
, lets call it R1
2
$b =& $a;
Here we are saying, point $b
to the same reference as$a
(R1)
3
$c = "eita";
$c
points to the reference for the string eita
, lets call it R2
4
$a =& $c;
Now we say, point $a
to the same reference as $c
($b
still points to R1)
At this stage,
$a
and $c
point to R2,
$b
points to R1
- should be easy to guess what happens next!
5
echo $b; // hihaha
We now know that echo
ing $b
will output R1!
Hope that helps!
Have a read of http://php.net/manual/en/language.references.whatdo.php
Upvotes: 0