PHP 通过引用删除
PHP Removing by reference
我正在尝试通过引用删除 stdClass 属性。因为不知道属性嵌套了多深,所以在循环中做了引用。但是 unset 方法不会通过引用删除变量。如何在不设置空值的情况下解决它?
<?php
$data = new stdClass();
$data->foo = new stdClass();
$data->foo->bar = 'value';
$pathToRemove = 'foo.bar';
$dataReference = &$data;
foreach (explode('.', $pathToRemove) as $field) {
$dataReference = &$dataReference->$field;
}
unset($dataReference);
var_dump($data);
遍历除最后一个元素之外的所有元素。然后将最后一个元素作为要删除的字段。
$pathArray = explode('.', $pathToRemove);
$lastField = array_pop($pathArray);
$dataReference = &$data;
foreach ($pathArray as $field) {
$dataReference = &$dataReference->{$field};
}
unset($dataReference->{$lastField});
unset($dataReference); // don't need the reference variable any more
我正在尝试通过引用删除 stdClass 属性。因为不知道属性嵌套了多深,所以在循环中做了引用。但是 unset 方法不会通过引用删除变量。如何在不设置空值的情况下解决它?
<?php
$data = new stdClass();
$data->foo = new stdClass();
$data->foo->bar = 'value';
$pathToRemove = 'foo.bar';
$dataReference = &$data;
foreach (explode('.', $pathToRemove) as $field) {
$dataReference = &$dataReference->$field;
}
unset($dataReference);
var_dump($data);
遍历除最后一个元素之外的所有元素。然后将最后一个元素作为要删除的字段。
$pathArray = explode('.', $pathToRemove);
$lastField = array_pop($pathArray);
$dataReference = &$data;
foreach ($pathArray as $field) {
$dataReference = &$dataReference->{$field};
}
unset($dataReference->{$lastField});
unset($dataReference); // don't need the reference variable any more