Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Destructor

The destructor is a magic method in a class, which is called at shutdown of an object, in order to do any last minute cleaning. It is called __destruct.

Most of the time, the destructor is automatic: removing scalar values may be sufficient. In cases of resources, or other objects, it is recommended to issue the graceful commands to shut them down in turn.

Destructors are usually called after the end of the script, and has no access to any display, including stdout. As such, calls to echo are ineffective, and it is recommended to store the needed logs in another system.

<?php

class Elephpant {
    private $file;

    function __construct($path) {
        $this->file = fopen($path, 'w');
    }

    function __destruct() {
        fwrite($this->file, 'End');
        fclose($this->file);
    }
}

$elephpant = new Elephpant('/tmp/test.txt');
unset($elephpant);

?>

Documentation

See Also