代码之家  ›  专栏  ›  技术社区  ›  Roman

我可以通过使一个数组等于另一个数组来分配它吗?

  •  6
  • Roman  · 技术社区  · 14 年前

    我有一个数组 $x 元素数不为零。我想创建另一个数组( $y . 然后我想用它做一些操作 $y年 不会引起任何变化 . 我能创造吗 $y年

    $y = $x;
    

    换句话说,如果我修改 $y年 以上面显示的方式创建,我将更改 ?

    3 回复  |  直到 14 年前
        1
  •  11
  •   Felix Kling    14 年前

    让我们试一下:

    $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

    数组分配总是涉及 . 使用引用运算符按引用复制数组。

        2
  •  2
  •   Matteo Riva    14 年前

    不,复印件不能改变原件。

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

    数组按值复制。这里有一个gotcha tho。如果某个元素是引用,则该引用将被复制,但引用的对象相同。

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