I need to clone an object, then remove some properties from the clone. Using unset()
on the cloned object works fine, but not on the cloned objects array of objects. I have simplified the object as it has quite a few more properties but the premise is the same.
$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:
";
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!:
";
print_r($testobject);
I expect the $testobject not to change, but it does. Why?!
I have re-created the format in a 3v4l here
question from:
https://stackoverflow.com/questions/65943087/unsetting-properties-in-array-of-objects-where-parent-is-a-clone 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…