Jump to content

[OOP] __destruct()


Altec

Recommended Posts

I'm just not getting in to OOP (I understand the basic concept), and just learned about the __destruct() function. I'm a little bit stuck as to using it appropriately.

 

For instance, if I define a public variable:

 

class Car {
    public $car;
}

And nothing happens to $car, wouldn't my destruct function look like this:

function __destruct() {
    if(empty($this->car)) {
        unset($car);
    }
}

Link to comment
Share on other sites

You're not defining $car as a "public" variable. You're defining it as an attribute of your Car class, that is accessible publicly (i.e. from outside of the class).

$x = new Car('Ford');
echo $x->car;

 

The destructor is only called when an instance of the Car object is destroyed (unset, etc), at which point all the attributes for that instance of Car are destroyed anyway because they are attributes of the instance that you're destroying.

 

Link to comment
Share on other sites

When just starting with OOP don't bother too much about __destruct().

 

You may need to redefine it for example, if your object can instantiate other objects during its lifetime. __destruct should then take care of destroing those "child" objects before destroying "main" object.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.