Hubro
Hubro

Reputation: 59333

Can I detect when my class instance gets unset or garbage-collected?

I have a PHP class that, upon instantiation, creates a file that is unique to that instance of my class. In fact, the entire class is more of a wrapper around the file with various functions to operate on the file.

I would like the file to get removed when the class is deleted/unset/garbage-collected. Is this possible? I'm looking for some sort of magic function that PHP calls on every object to give it a chance to get it's affairs in order before it's killed.

Upvotes: 1

Views: 105

Answers (2)

driangle
driangle

Reputation: 11779

class MyClass {

   function __destruct() {
       print "This instance is being destroyed!!! :(( ";
   }
}

Upvotes: 1

jjs9534
jjs9534

Reputation: 475

Yes, use a destructor method.

http://php.net/manual/en/language.oop5.decon.php

Upvotes: 4

Related Questions