2010-06-16 64 views
4

我有一个数组$x与非零数量的元素。我想创建另一个数组($y),它等于$x。然后,我想对$y进行一些操作,而不会对$x进行任何更改。我可以通过这种方式创建$y我可以通过使其等于另一个数组来分配一个数组吗?

$y = $x; 

换句话说,如果我修改了上面显示的方式创建$y,我会改变的$x价值?

+4

天哪!这很容易测试......写这个问题所需的时间要比编写一个简单的测试来知道你想知道的要多。 – Cristian 2010-06-16 14:43:57

+1

你让PHP和python混淆。 – Umang 2010-06-16 14:46:10

回答

9

让我们试试看:

$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 
) 

而且documentation说:

阵列分配总是涉及值复制。使用引用运算符通过引用复制数组。

1

不,原件不会改变原件。

如果使用原来的数组的引用它要改变它:

$a = array(1,2,3,4,5); 
$b = &$a; 
$b[2] = 'AAA'; 
print_r($a); 
1

数组被按值复制。有一个难题。如果元素是引用,则引用被复制但引用同一个对象。

<?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 
       ) 

     ) 

) 
*/ 
相关问题