rinogo
rinogo

Reputation: 9163

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!

Upvotes: 14

Views: 34367

Answers (8)

m13r
m13r

Reputation: 2731

With RedBean 4 you can use

unset($bean->someproperty);

Upvotes: 1

Fabien Snauwaert
Fabien Snauwaert

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

user3410818
user3410818

Reputation: 61

RedBean has a removeProperty method on beans.

Upvotes: 3

mario
mario

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

RobertPitt
RobertPitt

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

Jon
Jon

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

mhitza
mhitza

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

Prisoner
Prisoner

Reputation: 27628

Possibly unset().

Upvotes: 1

Related Questions