我有一个非空数组$x
。我想创建另一个数组($y
),它与$x
相等。然后,我想对$y
进行一些操作,而不会对$x
造成任何更改。我可以这样创建$y
吗:
$y = $x;
换句话说,如果我以上面展示的方式修改
$y
,那么$x
的值会改变吗?让我们试一试:
$a = array(0,1,2);
$b = $a;
$b[0] = 5;
print_r($a);
print_r($b);
提供
Array
(
[0] => 0
[1] => 1
[2] => 2
)
Array
(
[0] => 5
[1] => 1
[2] => 2
)
而且文档说:
数组赋值总是涉及值复制。使用引用操作符通过引用复制数组。
$a = array(1,2,3,4,5);
$b = &$a;
$b[2] = 'AAA';
print_r($a);
数组是按值复制的。但是需要注意的是,如果一个元素是引用类型,那么引用会被复制,但是仍然指向同一个对象。
<?php
class testClass {
public $p;
public function __construct( $p ) {
$this->p = $p;
}
}
// create an array of references
$x = array(
new testClass( 1 ),
new testClass( 2 )
);
//make a copy
$y = $x;
print_r( array( $x, $y ) );
/*
both arrays are the same as expected
Array
(
[0] => Array
(
[0] => testClass Object
(
[p] => 1
)
[1] => testClass Object
(
[p] => 2
)
)
[1] => Array
(
[0] => testClass Object
(
[p] => 1
)
[1] => testClass Object
(
[p] => 2
)
)
)
*/
// change one array
$x[0]->p = 3;
print_r( array( $x, $y ) );
/*
the arrays are still the same! Gotcha
Array
(
[0] => Array
(
[0] => testClass Object
(
[p] => 3
)
[1] => testClass Object
(
[p] => 2
)
)
[1] => Array
(
[0] => testClass Object
(
[p] => 3
)
[1] => testClass Object
(
[p] => 2
)
)
)
*/