Let's say that we have class CFoo
. In the following example when is CFoo::__destruct()
called?
function MyPHPFunc()
{
$foo = new CFoo();
. . .
// When/where/how does $foo get destroyed/deleted?
}
In this example would the destructor be called when the script exits the scope of MyPHPFunc
because $foo
would no longer be accessible?
In PHP all values are saved in so called
zval
s. Thosezval
s contain the actual data, type information and - this is important for your question - a reference count. Have a look at the following snippet:As soon as the
refcount
reaches0
thezval
is freed and the object destructor is called.Here are some examples of the
refcount
reaching0
:unset
ing a variable:But:
leaving function (or method) scope
script execution end
These obviously are not all conditions leading to a reduction of
refcount
, but the ones you will most commonly meet.Also I should mention that since PHP 5.3 circular references will be detected, too. So if object
$a
references object$b
and$b
references$a
and there aren't any further references to$a
or$b
therefcount
s of both will be1
, but they still will be freed (and__destruct
ed). In this case though the order of destruction is undefined behavior.the best way to know is to test.
however the simple answer is that __destruct is called during garbage cleanup. coarse that does not help anyone as garbage cleanup is an ongoing process that cleans up local variables when there is no scope that can call them.
however here is some sample code, and the result which fully explains what happens when exiting scope internally to the script.
the output of this strange set of classes function and vars is this
this shows us that the end of the function calls the __destruct, as does unset, and that at least in practice that end of script cleanup is done in reverse order created.
if create instance of a class and use the object.after finishing all your tasks if u call the destructor and again use the same object in the next line to perform some other task u will be no longer able to use. That means ur destructor is called successfully
If you want to see the process in action, you can run this code here.
The information is in the manual, albeit somewhat cryptic:
Meaning: The destructor will be called when the object gets destroyed (= e.g.
unset()
), or when the script shuts down.Additional useful info: