【问题标题】:PHP Removing by referencePHP 通过引用删除
【发布时间】:2021-12-30 14:47:04
【问题描述】:

我正在尝试通过引用删除 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);

【问题讨论】:

  • 是的,您可以使用 null 或 unset,如果没有指向同一引用的变量,它将被删除,请参阅 php.net/manual/en/features.gc.php 也可以使用 php.net/manual/en/function.gc-collect-cycles.php
  • 这是因为如果您使用引用,那么unset 将释放引用。在您的示例中:您要删除bar,还是全部删除。 foo ?
  • 我只想删除 bar 字段。这个例子很简单,我有很多不同的领域。我想完全删除该字段,将其设置为 null 仍然会显示它。
  • 那么来自@Barmar 的答案就是您所需要的。注意:他取消了$referenceVar-&gt;$property。所以不要自己参考。

标签: php unset stdclass


【解决方案1】:

遍历除最后一个之外的所有元素。然后将最后一个元素作为要删除的字段。

$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

【讨论】:

  • $path_array 应该是$pathArray
  • 有效。最后建议unset($dataReference); 释放引用(以后不会意外更改$data)。我建议$dataReference-&gt;{$lastField}(使用{})。
猜你喜欢
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多