复制包含对象的PHP数组项

时间:2013-08-07 17:45:41

标签: php arrays object reference copy

我想复制一个包含对象的数组项。

$arr = [
    'first_item' => [
        'label' => 'a',
        'date' => new DateTime('1999-12-30')
    ],
    'second_item' => [
        'label' => 'b',
        'date' => new DateTime('1999-12-31')
    ]
];

$copy = $arr['second_item'];
$copy['label'] = 'c'; // OK, does not affect $arr['second_item']
$copy['date']->setDate(2000, 1, 1); // changes $arr['second_item'] as well

只是出于想法,我尝试将$copy = $arr['second_item']替换为$copy = clone $arr['second_item'],但它(可以理解)失败并出现*“致命错误:在非对象上调用__clone方法”*消息。

0 个答案:

没有答案