Reputation: 9163
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!
Upvotes: 14
Views: 34367
Reputation: 5651
Do you want to unset the property merely because you do not want it stored in the database?
If so, just declare the property as private
in the class.
Kudos to this answer: Not saving property of a php-redbean to database
Upvotes: 0
Reputation: 145512
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.
Upvotes: 18
Reputation: 57268
within you object you can define a magic method called __unset
class Test
{
public $data = array();
public function __unset($key)
{
unset($this->data[$key]);
}
}
And Jon summed up the other factors nicely.
Upvotes: 5
Reputation: 437664
$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);
Upvotes: 11
Reputation: 5715
No you cannot, nor in the Runkit module do I see a way to accomplish that, even if ways to remove methods/functions/constants exist.
Upvotes: 1