是否可以在 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
Is it possible to delete an object's property in PHP?
提问by valk
If I have an stdObject
say, $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 unset
is 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 array
as 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.
无需使用括号。