0

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:\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);

I expect the $testobject not to change, but it does. Why?!

I have re-created the format in a 3v4l here

4
  • 1
    I'd like to direct you to an answer I've written earlier about a similar issue. Commented Jan 28, 2021 at 18:26
  • it's because the method clone will just clone the properties of a class if this properties isn't objects. objects will be referenced, so if you change that object on $testobject, $cloneobjec will change too Commented Jan 28, 2021 at 18:38
  • 1
    clone ain't recursive. Take a look at stackoverflow.com/questions/10831798/php-deep-clone-object Commented Jan 28, 2021 at 18:41
  • 1
    @nice_dev thanks for the tip. Used the unserialize(serialize()) method you linked to; works perfect. Thanks! Commented Jan 29, 2021 at 0:45

1 Answer 1

0

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 \n";
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!\n";
print_r($testobject);
echo "Copied object is now different than $testobject!\n";
print_r($cloneobject);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.