[php] Is it possible to delete an object's property in 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?

This question is related to php object

The answer is


This code is working fine for me in a loop

$remove = array(
    "market_value",
    "sector_id"
);

foreach($remove as $key){
    unset($obj_name->$key);
}

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.