Is it possible to delete an object's property in PHP?
PhpObjectPhp 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);