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

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


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.