Hướng dẫn php unset object property

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?

YakovL

6,91012 gold badges57 silver badges88 bronze badges

asked Aug 30, 2010 at 13:25

Hướng dẫn php unset object property

2

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())

answered Aug 30, 2010 at 13:26

Yanick RochonYanick Rochon

48.7k24 gold badges122 silver badges195 bronze badges

6

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})

Grzegorz

5,3241 gold badge27 silver badges49 bronze badges

answered Sep 9, 2014 at 15:07

Hướng dẫn php unset object property

Sajjad AshrafSajjad Ashraf

3,6241 gold badge33 silver badges34 bronze badges

2

This also works if you are looping over an object.

unset($object->$key);

No need to use brackets.

answered Feb 28, 2019 at 15:49

dandybohdandyboh

1171 silver badge2 bronze badges

1

This code is working fine for me in a loop

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

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

answered Jul 29, 2020 at 14:48

Ashiq DeyAshiq Dey

2572 silver badges13 bronze badges

1

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

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);

answered Jul 25, 2021 at 18:05

TexWillerTexWiller

3082 silver badges9 bronze badges