我想复制一个包含对象的数组项。
$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 方法”* 消息。