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开发者_如何学Go the array key in question, and convert back to an object, but blech... There's got to be an easier way!
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.
$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);
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.
RedBean has a removeProperty method on beans.
Possibly unset().
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.
With RedBean 4 you can use
unset($bean->someproperty);
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
精彩评论