是否可以在PHP中删除对象的属性?
问题描述:
If I have an stdObject
say, $a
.
Sure there's no problem to assign a new property, $a
,
$a->new_property = $xyz;
But then I want to remove it, so unset
is of no help here.
So,
$a->new_property = null;
is kind of it. But is there a more 'elegant' way?
答
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())
答
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
unset($object{$key})
答
This also works if you are looping over an object.
unset($object->$key);
No need to use brackets.