14

Is there a way in PHP to destroy an object from within that same object?

hakre
  • 193,403
  • 52
  • 435
  • 836
Spot
  • 7,962
  • 9
  • 46
  • 55
  • 1
    gave a "yes-and-here-is-how" answer to an essentially similar question here - http://stackoverflow.com/a/21367011/1537018 – Jaak Kütt Jan 26 '14 at 18:07
  • No, I don't think there is. But would you need such thing? – RaYell Sep 12 '09 at 09:03
  • @Christian the ability to destroy an object leis in the same place where the ability to create them - not inside the object itself. – Jaak Kütt Jan 26 '14 at 09:43

2 Answers2

12

If a method is called in the object's context then there has to be at least one reference to that object. And since php only removes unreachable objects the answer is: no.

VolkerK
  • 95,432
  • 20
  • 163
  • 226
7

There is a way to self destruct an object :

Use the $GLOBALS array to find your instance in it, then use unset(). Be aware that unset() does not automatically call the __destruct() magic method all the time...

There is such a note in this way (see the unset() documentation) in the PHP documentation, but it does not explain exactly when unset() does not call the __destruct() method.

And I had this specific behaviour :

I do a :

unset($myInstance);
$myInstance = clone $otherInstance;

And the __constructor is called first, then the __destruct(). Or I would like the __destruct() to be called first because unset() is before clone... I ma stuck with that now...

Nicolas.

Jay D
  • 3,263
  • 4
  • 32
  • 48
sauvaget
  • 86
  • 1
  • 1
  • 2
    Destructors are called on garbage collection or when the script terminates. – hakre Aug 08 '11 at 18:20
  • As hakre stated, until the $myInstance variable is out of scope and garbage collection picks it up, the destructor will not be called. – Swivel Jul 12 '13 at 19:28