Php 我可以通过使数组等于另一个数组来分配数组吗?
我有一个数组Php 我可以通过使数组等于另一个数组来分配数组吗?,php,arrays,Php,Arrays,我有一个数组$x,元素数为非零。我想创建另一个数组($y),它等于$x。然后我想使用$y进行一些操作,而不引起对$x的任何更改。我可以这样创建$y: $y = $x; 换句话说,如果我修改以上述方式创建的$y,我会更改$x的值吗?否,副本不会更改原件 如果使用对原始数组的引用,则会更改它: $a = array(1,2,3,4,5); $b = &$a; $b[2] = 'AAA'; print_r($a); 让我们试一试: $a = array(0,1,2); $b = $a; $
$x
,元素数为非零。我想创建另一个数组($y
),它等于$x
。然后我想使用$y
进行一些操作,而不引起对$x
的任何更改。我可以这样创建$y
:
$y = $x;
换句话说,如果我修改以上述方式创建的
$y
,我会更改$x
的值吗?否,副本不会更改原件
如果使用对原始数组的引用,则会更改它:
$a = array(1,2,3,4,5);
$b = &$a;
$b[2] = 'AAA';
print_r($a);
让我们试一试:
$a = array(0,1,2);
$b = $a;
$b[0] = 5;
print_r($a);
print_r($b);
给予
报告说:
数组赋值总是涉及值复制。使用引用运算符按引用复制数组
数组是按值复制的。这里有一个gotchatho。如果某个元素是引用,则复制该引用,但引用同一对象
<?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
)
)
)
*/
天哪!这太容易测试了。。。写这些问题所需的时间比写一个简单的测试来了解你想知道的要多,你把PHP和python搞混了。
<?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
)
)
)
*/