Using __destruct()
Alongside the constructor, the destructor is a common feature of the OO language. The __destruct()
magic method represents this concept. The method gets triggered as soon as there are no other references to a particular object. This can happen either when PHP decides to explicitly free the object, or when we force it using the unset()
 language construct.
As with constructors, parent destructors don't get called implicitly by PHP. In order to run a parent destructor, we need to explicitly call parent::__destruct()
. Furthermore, the child class inherits the parent's destructor if it does not implement one for itself.
Let's say we have a following simple User
class:
<?php class User { public function __destruct() { echo '__destruct'; } }
With the User
class in place, let's go ahead and look through instance creation examples:
echo 'A'; new User(); echo 'B'; // outputs "A__destructB"
The new User();
 expression here instantiates an instance of the User
class...