Search code examples
phpoopdestructorphp-7magic-methods

Does __destruct run by itslef or do I need to use unset() or register_shutdown_function() in order for it to work


a) Does __destruct run every single time a code is processed, just by itself

b) Or, no, you need to use unset($objectName) in order for it to run (another option is register_shutdown_function() ).

c) Are there any other aspects related to this? Like it works by itself when this or that, and you can also use this or that in order for it to run, anything...


Solution

  • No, the unset() function is not the only way to call __destruct(). According to the documentation, “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”.

    To illustrate this, consider the following methods when __destruct() will be called automatically:

    1) It is called instantly when the class instance is not assigned to any variable:

    <?php
    new TheClass(); #-> this line calls __destruct()
    
    /* More PHP Code */
    ?>
    

    2) It is called when script execution is stopped:

    <?php
    $obj = new TheClass();
    exit; #-> this line calls __destruct()
    
    /* More PHP Code */
    ?>
    

    3) It is called when unset() destroys the reference of the class:

    <?php
    $obj = new TheClass();
    unset($obj); #-> this line calls __destruct()
    
    /* More PHP Code */
    ?>
    

    4) It is called when the value of variable is reassigned:

    <?php
    $obj = new TheClass();
    $obj = 'any value'; #-> this line calls __destruct()
    
    /* More PHP Code */
    ?>
    

    5) It is called when the script completes its execution:

    <?php
    $obj = new TheClass();
    
    /* More PHP Code */
    
    #-> this line calls __destruct()
    ?>
    

    6) It is called when exiting variable scope:

    <?php
    call_user_func(function() {
        $obj = new TheClass();
    
        /* More PHP Code */
    
        return true; #-> this line calls __destruct()
    });
    
    /* More PHP Code */
    ?>