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

PhpObject

Php Problem Overview


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?

Php Solutions


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

Solution 2 - Php

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

Solution 3 - Php

This also works if you are looping over an object.

unset($object->$key);

No need to use brackets.

Solution 4 - Php

This code is working fine for me in a loop

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

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

Solution 5 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvalkView Question on Stackoverflow
Solution 1 - PhpYanick RochonView Answer on Stackoverflow
Solution 2 - PhpSajjad AshrafView Answer on Stackoverflow
Solution 3 - PhpdandybohView Answer on Stackoverflow
Solution 4 - PhpAshiq DeyView Answer on Stackoverflow
Solution 5 - PhpTexWillerView Answer on Stackoverflow