1.2.1100. Should Have Destructor

PHP destructors are called when the object is being destroyed. By default, PHP calls recursively the destructor on internal objects, until everything is unset.

Unsetting objects and resources explicitly in the destructor is a good practice to reduce the amount of memory in use. It helps PHP resource counter to keep the numbers low, and easier to clean. This is a major advantage for long running scripts.

Unsetting scalar properties, such as string or int is not necessary, as they are stored independently and cleaned automatically by PHP. Closing resources of type resource is important : there might be some final calls to close it cleanly. Unsetting an object only decreases the reference count for that object : it is still available to other objects that kept it as property.

Destructor is useful for long-running resources : file resource, sockets, a file lock or persistent database connexion. This is a good time to finish cleanly, and close.

Internally to the application, destructors are also useful with static properties and registries : for example, the current class may deregister from a list of listener, so that this list is still up to date. Otherwise, the registry keeps the object alive.

<?php

class x {
    function __construct() {
        $this->p = new y();
    }

    function __destruct() {
        print __METHOD__.PHP_EOL;
        unset($this->p);
    }
}

class y {
    function __construct() {
        print __METHOD__.PHP_EOL;
        $this->p = new y();
    }

    function __destruct() {
        print __METHOD__.PHP_EOL;
        unset($this->p);
    }
}

$a = (new x);
sleep(1);

// This increment the resource counter by one for the property.
$p = $a->p;
unset($a);
sleep(3);

print 'end'.PHP_EOL;
// Y destructor is only called here, as the object still exists in $p.

?>

See also Destructor and Php Destructors.

1.2.1100.1. Suggestions

  • Add a destruct method to the class to help clean at destruction time.

1.2.1100.2. Specs

Short name

Classes/ShouldHaveDestructor

Rulesets

All, Suggestions

Exakat since

1.5.4

PHP Version

All

Severity

Minor

Time To Fix

Slow (1 hour)

Precision

Very high

Features

destructor

Available in

Entreprise Edition, Exakat Cloud