【发布时间】:2021-05-02 16:49:12
【问题描述】:
我需要克隆一个对象,然后从克隆中删除一些属性。在克隆对象上使用unset() 可以正常工作,但不能在克隆对象数组上使用。我已经简化了这个对象,因为它有更多的属性,但前提是一样的。
$testobject = new stdClass();
$testobject->propertya = 'banana';
$testobject->propertyb = 'orange';
$testobject->propertyc = 'apple';
$testobject->childarray = array();
$testobject->childarray[] = new stdClass();
$testobject->childarray[0]->childpropertya = 'cola';
$testobject->childarray[0]->childpropertyb = 'bread';
$testobject->childarray[0]->childpropertyc = 'pasta';
echo "Original object:\n";
print_r($testobject);
$cloneobject = clone $testobject;
unset($cloneobject->propertyb);
foreach ($cloneobject->childarray as $index => $data) {
unset ($data->childpropertya);
}
unset($cloneobject->childarray['childpropertyc']);
echo "Original object expected to be the same but is NOT!:\n";
print_r($testobject);
我希望 $testobject 不会改变,但确实如此。为什么?!
我在3v4l here 中重新创建了格式
【问题讨论】:
-
我想将您转至answer I've written earlier,了解类似问题。
-
这是因为如果该属性不是对象,则方法 clone 只会克隆类的属性。对象会被引用,所以如果你在 $testobject 上改变那个对象,$cloneobjec 也会改变
-
@nice_dev 感谢您的提示。使用了您链接到的 unserialize(serialize()) 方法;完美运行。谢谢!