为什么在1个对象中更改值可以更改所有值的另一个对象?

时间:2016-11-02 15:41:17

标签: php arrays

当我想回答某人问题XD

时,我意外地发现了这个问题
<?php
/*
why change value in 1 object can change all value another object?
*/

function prints($a)
{
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

//CASE 1 : create object from array
$array = array(
    'id' => 1,
    'name' => 'albert'
);
$data = array(
    (object) $array,
    (object) $array
);
prints($data);
/*output
Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => albert
        )

    [1] => stdClass Object
        (
            [id] => 1
            [name] => albert
        )
)
*/


//CASE 2 : change value 2nd object of 2nd array 
$data[1]->name = 'john';
prints($data);
/* output
Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => albert
        )

    [1] => stdClass Object
        (
            [id] => 1
            [name] => john
        )
)
no question about this. 
only 2nd object of 2nd object will change
its know this clearly
*/

//create same object with different way
$obj = new stdClass();
$obj->id=1;
$obj->name='albert';
$data= array($obj, $obj);
prints($data);
/*output: this will be same as $data array in above
Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => albert
        )

    [1] => stdClass Object
        (
            [id] => 1
            [name] => albert
        )
)
*/

//THE PROBLEM
//change value 2nd object of 2nd array 
$data[1]->name="john";
prints($data);
/*output
Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => john
        )

    [1] => stdClass Object
        (
            [id] => 1
            [name] => john
        )

)
All key name in object will change to john , instead of only the 2nd.
How this could happen??
*/

?>
  

重新解释问题

CASE 1 中的

:我尝试将最后一个对象值(albert)更改为(john)。结果只有最后一个数组才会变为(john)。 [我知道]

IN CASE 2 :我以不同的方式生成相同的数组,然后我尝试像 CASE 1 中的相同内容。但结果是所有[name]都改为[john],而不是让对象1中的[name]为(albert),并将对象2中的[name]改为(john)

我很难知道这一点,但仍然无法从谷歌找到答案。 我发现了一些,但仍然无法向我解释^ _ ^ 7

我非常感谢任何解释。感谢

1 个答案:

答案 0 :(得分:0)

  

来自@ Rizier123的回答

案例2:我从 SAME OBJECT 创建数组:$ data = array($ obj,$ obj);

IN CASE 1:我从 DIFFERENT OBJECT 创建数组:$ data = array($ obj1,$ obj2);

是的,它在显示方面类似,但不在计算机内存中

$data = array(
    (object) $array, //computer maybe save it as $obj1 or any variable that i dont know the name XD
    (object) $array //computer maybe save it as $obj2
);

所以这是最后的代码解释

<?php
$array = array(
    'id' => 1,
    'name' => 'albert'
);
$obj1= (object) $array;
$obj2= (object) $array;
$obj3= (object) $array;
//CASE 1
$data = array($obj1, $obj2); //different object although it have same component

//CASE 2
$data = array($obj3, $obj3); //same object

?>

谢谢@Rizier123