Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the destructor called in PHP?

Tags:

php

destructor

I've read this answer:

Is destructor in PHP predictable?

But still fail to be 100% confident that the destructor is called as soon as the object goes out of scope.

My use case is the following:

class Transaction
{
    private $isComplete = false;

    public function commit() {
        // ...

        $this->isComplete = true;
    }

    public function rollBack() {
        // ...

        $this->isComplete = true;
    }

    public function __destruct() {
        if (! $this->isComplete) {
            $this->rollBack();
        }
    }
}

Say I'm using it this way:

function doSomething() {
    $tx = $this->txManager->beginTransaction();

    // ... code here may or may not throw an exception

    $tx->commit();
}

Can I be 100% confident that in all cases (exception or not), the destructor will be the first thing that will be called as soon as the function ends?

My initial testing shows that yes, exception or not, the destructor is called right away. But I'd like a confirmation, and above all, a pointer to the relevant documentation.

like image 335
BenMorel Avatar asked Jun 20 '26 16:06

BenMorel


2 Answers

From https://www.php.net/manual/en/language.oop5.decon.php#object.destruct

The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.


In your case it would happen when there is no more reference to $tx anywhere. This would be as soon as we are done with doSomething(), except if there is for example another reference stored in txManager.

A destructor is called when the object is destructed or the script is stopped or exited. If you create a __destruct() function, PHP will automatically call this function at the end of the script.

DEMO

like image 44
norcal johnny Avatar answered Jun 23 '26 17:06

norcal johnny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!