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

后端 未结 4 524
无人共我
无人共我 2020-11-29 03:02

If I have an stdObject say, $a.

Sure there\'s no problem to assign a new property, $a,

$a->new_property = $         


        
相关标签:
4条回答
  • 2020-11-29 03:39

    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})
    
    0 讨论(0)
  • 2020-11-29 03:39

    This also works if you are looping over an object.

    unset($object->$key);
    

    No need to use brackets.

    0 讨论(0)
  • 2020-11-29 03:50
    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())
    
    0 讨论(0)
  • 2020-11-29 03:57

    This code is working fine for me in a loop

    $remove = array(
        "market_value",
        "sector_id"
    );
    
    foreach($remove as $key){
        unset($obj_name->$key);
    }
    
    0 讨论(0)
提交回复
热议问题