【问题标题】:Unsetting properties in array of objects where parent is a clone取消设置父对象是克隆的对象数组中的属性
【发布时间】: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()) 方法;完美运行。谢谢!

标签: php arrays object clone


【解决方案1】:

已解决,感谢@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);

【讨论】:

    猜你喜欢
    • 2016-08-05
    • 2018-08-08
    • 2015-02-08
    • 2018-12-07
    • 2014-05-02
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多