首页 > 解决方案 > 将变量(数组)分配给其他变量不会从源变量中获取副本

问题描述

假设这样的代码:

$a = [1,2];
$b = &$a;     // $b holds reference to $a
$b[] = 3;     // so this makes $a to {1,2,3}
$b = $a;      // $b now holds COPY of $a (not reference)
$b[] = 4;     // so $a must be the same {1,2,3}
var_dump($a); // but it isn't - $a is {1,2,3,4}

因此,不知何故,语句$b = $a;并没有按照应有的方式分配 $a 数组的新副本,而是仅使用它的引用。这是为什么 ?

标签: phparraysreference

解决方案


推荐阅读