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
https://forums.phpfreaks.com/topic/136311-oop-__destruct/
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
https://forums.phpfreaks.com/topic/136311-oop-__destruct/#findComment-711306
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
https://forums.phpfreaks.com/topic/136311-oop-__destruct/#findComment-711311
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.