是否可以在 PHP 中删除对象的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3600750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:22:14  来源:igfitidea点击:

Is it possible to delete an object's property in PHP?

phpobject

提问by valk

If I have an stdObjectsay, $a.

如果我有stdObject发言权,$a.

Sure there's no problem to assign a new property, $a,

当然分配新属性没有问题$a

$a->new_property = $xyz;

But then I want to remove it, so unsetis of no help here.

但后来我想删除它,所以unset在这里没有帮助。

So,

所以,

$a->new_property = null;

is kind of it. But is there a more 'elegant' way?

是种吧。但还有更“优雅”的方式吗?

回答by Yanick Rochon

unset($a->new_property);

This works for array elements, variables, and object attributes.

这适用于数组元素、变量和对象属性。

Example:

例子:

$a = new stdClass();

$a->new_property = 'foo';
var_export($a);  // -> stdClass::__set_state(array('new_property' => 'foo'))

unset($a->new_property);
var_export($a);  // -> stdClass::__set_state(array())

回答by Sajjad Ashraf

This also works specially if you are looping over an object.

如果您正在循环对象,这也特别有效。

unset($object[$key])

Update

更新

Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as arrayas mentioned by @CXJ . In that case you can use brackets instead

Fatal error: Cannot use object of type Object as array如@CXJ 所述,较新版本的 PHP 会引发致命错误。在这种情况下,您可以使用括号代替

unset($object{$key})

回答by dandyboh

This also works if you are looping over an object.

如果您正在循环对象,这也适用。

unset($object->$key);

No need to use brackets.

无需使用括号。