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

Viewed 261783

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?

5 Answers

This also works if you are looping over an object.

unset($object->$key);

No need to use brackets.

This code is working fine for me in a loop

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

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

Set an element to null just set the value of the element to null the element still exists

unset an element means remove the element it works for array, stdClass objects user defined classes and also for any variable

<?php
    $a = new stdClass();
    $a->one = 1;
    $a->two = 2;
    var_export($a);
    unset($a->one);
    var_export($a);
    
    class myClass
    {
        public $one = 1;
        public $two = 2;
    }
    
    $instance = new myClass();
    var_export($instance);
    unset($instance->one);
    var_export($instance);
    
    $anyvariable = 'anyValue';
    var_export($anyvariable);
    unset($anyvariable);
    var_export($anyvariable);
Related