8

Is a class destructor in PHP predictable? When is the destructor called?

Like in many languages, will a class destructor be called as soon as the object goes out of scope?

Hemanshu Bhojak
  • 16,972
  • 16
  • 49
  • 64

2 Answers2

11

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.

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

Ahmed Aman
  • 2,373
  • 1
  • 19
  • 33
  • 2
    Indeed, as all references are gone, not necessarily if a variable goes out of scope. – Wrikken Jul 24 '10 at 17:02
  • 1
    this also includes when the script itself finishes executing. – CrayonViolent Jul 24 '10 at 19:04
  • But how can I call destructors in case of the script not finishes cleanly? In Windows, for an example, when killing a process, all ref-counted resources are automatically decremented on the same count they were incremented before the crash. I need to send a packet for session cleanup to another server in case of exception too. – Brian Cannard Sep 05 '14 at 11:44
4

It's called when the first of these conditions are met:

  • The reference count of the object goes to 0 (these usually happens when the object has no more variables that reference it -- they were unset or went out of scope --, but it can happen later, as an object may be referenced by something other than a variable -- in fact, the reference count is just a number and can be manipulated in an arbitrary way).
  • When using PHP 5.3, when the garbage collector detects the positive reference count is due to circular references.
  • Otherwise, when the script finishes cleanly.

In short, you should not rely on it always being called, because the script may not finish cleanly.

Artefacto
  • 96,375
  • 17
  • 202
  • 225