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
zvals. Thosezvals 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
refcountreaches0thezvalis freed and the object destructor is called.Here are some examples of the
refcountreaching0:unseting 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
$areferences object$band$breferences$aand there aren’t any further references to$aor$btherefcounts of both will be1, but they still will be freed (and__destructed). In this case though the order of destruction is undefined behavior.