当保存它的原始变量具有新的引用值时,引用值如何保留在内存中?
How can a referenced value stay in memory when the original variable that holds it has a new referenced value?
我在 PHP docs comments 中发现了这个非常古老的评论,但我无法理解为什么它在第一个示例中输出 "hihaha" 而不是 "eita"。 $a
已更改,我认为 "hihaha"
已永久删除。如果不是,那么为什么要更改 null
或分配另一个变量的副本,然后 "hihaha"
被永久删除?
// 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"
这是"good way"循环引用问题吗?
将变量视为指向引用 - 分解示例 1...
1
$a = "hihaha";
$a
指向字符串 hihaha
的引用,我们称它为 R1
2
$b =& $a;
我们在这里说,将$b
指向与$a
相同的引用(R1)
3
$c = "eita";
$c
指向字符串 eita
的引用,我们称它为 R2
4
$a =& $c;
现在我们说,将$a
指向与$c
相同的引用($b
仍然指向R1)
现阶段,
$a
和 $c
指向 R2,
$b
指向 R1
- 应该很容易猜到接下来会发生什么!
5
echo $b; // hihaha
我们现在知道 echo
ing $b
将输出 R1!
希望对您有所帮助!
从 $a = "hihaha";
开始,当您执行 $b = &$a;
时,$b
是 而不是 引用 $a
。它引用了 $a
的 content。正如 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.
然后在 $c = "eita";
之后,当您执行 $a = &$c;
时,$a
现在正在引用 $c
("eita") 的内容。
这根本不会影响 $b
。 $b
仍然引用 $a
("hihaha") 的原始内容。将 $a
指向其他东西不会改变这一点。
如果您有更多的 mspaint 学习风格,这里有一个表示示例 1 的前四个语句的视觉帮助:
在第二个例子中,当$a
设置为null
时,$a
和$b
仍然指向相同的内容,所以$b
是现在也引用 null
。视觉上:
我在 PHP docs comments 中发现了这个非常古老的评论,但我无法理解为什么它在第一个示例中输出 "hihaha" 而不是 "eita"。 $a
已更改,我认为 "hihaha"
已永久删除。如果不是,那么为什么要更改 null
或分配另一个变量的副本,然后 "hihaha"
被永久删除?
// 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"
这是"good way"循环引用问题吗?
将变量视为指向引用 - 分解示例 1...
1
$a = "hihaha";
$a
指向字符串 hihaha
的引用,我们称它为 R1
2
$b =& $a;
我们在这里说,将$b
指向与$a
相同的引用(R1)
3
$c = "eita";
$c
指向字符串 eita
的引用,我们称它为 R2
4
$a =& $c;
现在我们说,将$a
指向与$c
相同的引用($b
仍然指向R1)
现阶段,
$a
和 $c
指向 R2,
$b
指向 R1
- 应该很容易猜到接下来会发生什么!
5
echo $b; // hihaha
我们现在知道 echo
ing $b
将输出 R1!
希望对您有所帮助!
从 $a = "hihaha";
开始,当您执行 $b = &$a;
时,$b
是 而不是 引用 $a
。它引用了 $a
的 content。正如 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.
然后在 $c = "eita";
之后,当您执行 $a = &$c;
时,$a
现在正在引用 $c
("eita") 的内容。
这根本不会影响 $b
。 $b
仍然引用 $a
("hihaha") 的原始内容。将 $a
指向其他东西不会改变这一点。
如果您有更多的 mspaint 学习风格,这里有一个表示示例 1 的前四个语句的视觉帮助:
在第二个例子中,当$a
设置为null
时,$a
和$b
仍然指向相同的内容,所以$b
是现在也引用 null
。视觉上: