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

valk picture valk · Aug 30, 2010 · Viewed 196k times · Source

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?

Answer

Yanick Rochon picture Yanick Rochon · Aug 30, 2010
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())