拒绝通过链接传递变量

时间:2014-02-25 08:30:35

标签: php

$obj = new StdClass();
$obj->prop1 = 1;
$obj->prop2 = 2;
$a1 = array(
    0 => $obj,
    1 => $obj,
);
$a2 = $a1;
$a1[0]->prop1 = 100;
var_dump($a2);

目前的结果:

$a2 = array(
    0 => stdClass::__set_state(array(
        'prop1' => 100,
        'prop2' => 2
    )),
    1 => stdClass::__set_state(array(
        'prop1' => 100,
        'prop2' => 2
    ))
);

必填结果:

$a2 = array(
    0 => stdClass::__set_state(array(
        'prop1' => 1,
        'prop2' => 2
    )),
    1 => stdClass::__set_state(array(
        'prop1' => 1,
        'prop2' => 2
    ))
);

PHP 5.5.3-1ubuntu2.1

1 个答案:

答案 0 :(得分:1)

试试这个:

function deepClone(array $input) {
    $output = array();
    foreach($input as $key => $obj) {
        $output[$key] = clone $obj;
    }

    return $output;
}

$obj = new StdClass();
$obj->prop1 = 1;
$obj->prop2 = 2;
$a1 = array(
    0 => $obj,
    1 => $obj,
);
$a2 = deepClone($a1);
$a1[0]->prop1 = 100;
var_dump($a2);

但是我觉得你应该针对你的问题提出一个不同的方法,因为我倾向于尽可能避免clone