Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

php - Unsetting properties in array of objects where parent is a clone

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solved, thanks for the tip @nice_dev

$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 = unserialize(serialize($testobject));

unset($cloneobject->propertyb);
foreach ($cloneobject->childarray as $index => $data) {
    unset ($data->childpropertya);
}
unset($cloneobject->childarray['childpropertyc']);

echo "Original object is the same!
";
print_r($testobject);
echo "Copied object is now different than $testobject!
";
print_r($cloneobject);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...