Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a member from an object?

Is there a simple way to remove a member from an object? Not just set it to null, but actually remove it.

Thanks! :)

Edit: I've already tried unset(), and setting the member variable to null obviously doesn't work. I suppose I could convert the object to an array, then remove the array key in question, and convert back to an object, but blech... There's got to be an easier way!

like image 267
rinogo Avatar asked Mar 19 '11 00:03

rinogo


People also ask

How do I remove a property name from an object?

Remove Property from an ObjectThe delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.

How to remove a property in an object in JavaScript?

In JavaScript, there are 2 common ways to remove properties from an object. The first mutable approach is to use the delete object. property operator. The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax: const {property, ...

How do I remove a property from an object in C#?

You can't remove a property, unless you remove it permanently, for all cases. What you can do, however, is to create multiple classes, in a class hierarchy, where one class has the property and the other hasn't.

How to strip object in JavaScript?

There are two ways to remove a property from a JavaScript object. There's the mutable way of doing it using the delete operator, and the immutable way of doing it using object restructuring.


2 Answers

You are using RedBean. Just checked it out. And these bean objects don't have actual properties.

unset($bean->field);

Does not work, because ->field is a virtual attribute. It does not exist in the class. Rather it resides in the protected $bean->properties[] which you cannot access. RedBean only implements the magic methods __get and __set for retrieving and setting attributes.

This is why the unset() does not work. It unsets a property that never existed at that location.

like image 65
mario Avatar answered Oct 13 '22 00:10

mario


$obj = new stdClass;
$obj->answer = 42;
print_r($obj);
unset($obj->answer);
print_r($obj);

Works fine for me. Are you sure you 're doing it right?

Update:

It also works for properties defined in classes:

class Foo {
    public $bar = 42;
}

$obj = new Foo;
print_r($obj);
unset($obj->bar);
print_r($obj);
like image 23
Jon Avatar answered Oct 12 '22 23:10

Jon