【发布时间】:2014-10-02 19:16:49
【问题描述】:
我正在阅读这篇关于 PHP 变量引用的文章:http://derickrethans.nl/talks/phparch-php-variables-article.pdf 并想检查我的理解是否正确,关于何时创建新的变量容器。
对于非数组,每当您分配一个未指向设置了 is_ref 的容器的变量时,都会创建变量容器。
Ex 1 (let {..} be a container):
$a = 1; // "a" => {integer, 1, is_ref = 0, ref_count = 1}
$b = $a; // "a", "b" => {integer, 1, is_ref = 0, ref_count = 2}
$b = 2; // "a" => {integer, 1, is_ref = 0, ref_count = 1}
// "b" => {integer, 2, is_ref = 0, ref_count = 1}
Ex 2:
$a = 1; // "a" => {integer, 1, is_ref = 0, ref_count = 1}
$b = &$a; // "a", "b" => {integer, 1, is_ref = 1, ref_count = 2}
$b = 2; // "a", "b" => {integer, 2, is_ref = 1, ref_count = 2}
它如何用于数组?它看起来并不适用。例如,
$a = array(1, 2, 3);
$b = $a;
$c = &$b[2];
$c = 4;
print_r($a); // prints (1, 2, 3) instead of (1, 2, 4)
print_r($b); // prints (1, 2, 4)
我的期望:
$a 和 $b 指向同一个容器。在这个容器中,我们有 3 个 numeric_keys “0”、“1”、“2”,它们分别指向整数 1、2 和 3 的容器。
当我们执行$c = &$b[2] 时,我们会更新包含整数 3 的容器:
- is_ref = 0 变为 is_ref = 1
- ref_count = 1 变为 ref_count = 2。
当我们执行$c = 4 时,我们会更新包含整数 3 的容器:
- 由于设置了 is_ref,整数 3 变为整数 4
但是,我的期望有问题,因为最后是$a[2] != 4。我试图找出原因。我最好的猜测是,当我们尝试引用数组的元素或对象的属性时,PHP 引擎首先会检查数组/对象本身以查看 is_ref = 1。如果是,一切都按照我的预期进行。如果 is_ref = 0,那么会发生其他事情,这就是我所看到的。有人能告诉我那个“其他东西”是什么吗?
编辑 看起来这就是实际发生的情况。这段代码应该澄清一切!
$a = array(1, 2, 3);
$b = $a;
$c = &$b[2]; // $b points to a new container where $b[0], $b[1] still point to same container as $a[0], $a[1], but $b[2] points to a new container also pointed to by $c
$d = $b; // $d points to $b's container, this means changing $c will also change $d[2]
$d[0] = 5; // The container pointed to by $d[0] is the same as the one pointed to by $a[0] and $b[0]. Since this container has is_ref = 0, $d[0] will now point to a new container
// At this point $a = (1, 2, 3), $b = (1, 2, 3), $c = 3, $d = (5, 2, 3)
$d[2] = 25; // The container pointed to by $d[2] is the same as the one pointed to by $b[2] and $c. Since this container has is_ref = 1, Changing $d[2] will affect both $b[2] and $c.
// At this point $a = (1, 2, 3), $b = (1, 2, 25), $c = 25, $d = (5, 2, 25)
$e = $d[2]; // Since $d[2]'s container has is_ref = 1, $e will point to its own container
$c = 4; // Same idea as $d[2] = 25; except $e won't get affected
// At this point $a = (1, 2, 3), $b = (1, 2, 4), $c = 4, $d = (5, 2, 4), $e = 25
// only way to have $d[2] be different from $b[2] is to make the container's is_ref = 0
unset($b[2]);
unset($c);
$b[2] = $d[2];
$d[2] = 55;
// At this point $a = (1, 2, 3), $b = (1, 2, 4), $d = (5, 2, 25), $e = 25
【问题讨论】:
-
我不是 100% 确定,但我认为
$c = 4;将整数 4 定义为变量。所以它不再持有指向$b[2]的指针。所以$b[2]不包含“4”是有道理的。
标签: php arrays reference reference-counting