Home > Backend Development > PHP Tutorial > 关于引用, 这种情况谁能解释下

关于引用, 这种情况谁能解释下

WBOY
Release: 2016-06-23 14:13:10
Original
756 people have browsed it

代码段1:

$array_a		= array( 0 => 'a' );$array_b		= &$array_a;$array_c		= &$array_b;$array_d		= $array_b;$array_c[0]	= 'b';echo '变量a:';var_dump( $array_a );echo '变量b:';var_dump( $array_b );echo '变量c:';var_dump( $array_c );echo '变量d:';var_dump( $array_d );
Copy after login

输出结果:
变量a:array (size=1)  0 => string 'b' (length=1)变量b:array (size=1)  0 => string 'b' (length=1)变量c:array (size=1)  0 => string 'b' (length=1)变量d:array (size=1)  0 => string 'a' (length=1)
Copy after login

这里变量d值没变, 很好理解, 但改变一下变量c的引用位置, 如下:
代码段2:
$array_a		= array( 0 => 'a' );$array_b		= &$array_a;$array_c		= &$array_b[0];$array_d		= $array_b;$array_c	= 'b';echo '变量a:';var_dump( $array_a );echo '变量b:';var_dump( $array_b );echo '变量c:';var_dump( $array_c );echo '变量d:';var_dump( $array_d );
Copy after login

输出结果:
变量a:array (size=1)  0 => &string 'b' (length=1)变量b:array (size=1)  0 => &string 'b' (length=1)变量c:string 'b' (length=1)变量d:array (size=1)  0 => &string 'b' (length=1)
Copy after login

这里变量d也变了, 而且还变成了引用, 不理解为什么
求大神指教


回复讨论(解决方案)

手册里说了:如果具有引用的数组被拷贝,其值不会解除引用。对于数组传值给函数也是如此。

$array_c = &$array_b[0]; // 这样使得$array_b具有了引用,c与b[0]指向同一内存

上例子:

<?php/* 普通变量 */$a = 1;$b =& $a;$c = $b;$c = 7; //$c 的变化不影响 $a 或 $b ,$a和$b 仍指向 1/* 数组 */$arr = array(1);$a =& $arr[0]; //$a 和 $arr[0] 指向相同$arr2 = $arr; //未加 & 赋值$arr2[0]++;/* $a == 2, $arr == array(2) *//* 即使不是引用赋值,也一样改变了 */?>
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template