php copying array elements by value, not by reference

前端 未结 6 1994
清歌不尽
清歌不尽 2020-12-06 05:48

I have the following code:

$data[\'x\'] = $this->x->getResults();  

$data[\'y\'] = $data[\'x\'];

//some code here to modify $data[\'y\']
//this cause         


        
6条回答
  •  情歌与酒
    2020-12-06 06:15

    If you are working with objects, you might want to take a look at clone, to create a copy of an object, instead of a reference.

    Here is a very short example :

    First, with an array, it works by value :

    $data['x'] = array(
        'a' => 'test',
        'b' => 'glop',
    );
    $data['y'] = $data['x'];
    $data['y'][0] = 'Hello, world!';
    var_dump($data['x']); // a => test : no problem with arrays
    

    By default, with objects, it works by reference :

    $data['x'] = (object)array(
        'a' => 'test',
        'b' => 'glop',
    );
    $data['y'] = $data['x'];
    $data['y']->a = 'Hello, world!';
    var_dump($data['x']); // a => Hello, world! : objects are by ref
    

    But, if you clone the object, you work on a copy :
    I guess this is your case ?

    $data['x'] = (object)array(
        'a' => 'test',
        'b' => 'glop',
    );
    $data['y'] = clone $data['x'];
    $data['y']->a = 'Hello, world!';
    var_dump($data['x']); // a => test : no ref, because of cloning
    

    Hope this helps,

提交回复
热议问题