Skip to main content

The __destruct() Function

__destruct() is a special class method that PHP calls automatically when an object is destroyed or when the script ends.

You can think of it as the counterpart of __construct(): one runs as an object begins its life, the other as that life ends.

Once a class has a __destruct() function, PHP will call it for you at the end of the script, with no call needed in your own code.

As with the constructor, the name begins with two underscores (__).

The next example puts both special functions together: __construct() runs when each object is created, and __destruct() runs when the script reaches its end:

Destructor Example

The __destruct() function displays each fruit's details once the script ends:

Prompt
Write a PHP script that defines a Fruit class with a __construct() function and a __destruct() function. Create two Fruit objects and let the destructor display their details at the end of the script.
Output: PHP script

Useful Tip

Tip: Constructors and destructors are worth using because they cut down on the code you have to write.