1

I was wondering about the behavior of the magic method __destruct() and so I wrote a little test case that doesn't give me the outcome I would expect. Can someone clarify this for me?

I always thought that exit() would stop PHP from executing and in this case wouldn't be able to call __destruct().

PHP Version

PHP 7.1.8-2+ubuntu14.04.1+deb.sury.org+4 (cli) (built: Aug  4 2017 14:30:23) ( NTS )

Code

class DestructorTest
{
    public function __construct()
    {
        print "Constructed\n";
    }

    public function doSomething()
    {
        print "Doing something\n";
        exit("Exiting...\n");
    }

    public function somethingElse()
    {
        print "Doing something else\n";
    }

    public function __destruct()
    {
        print "Destructing\n";
        $this->somethingElse();
        exit("Final exit\n");
    }
}

$destruct = new DestructorTest();
$destruct->doSomething();

Output

Constructed
Doing something
Exiting...
Destructing
Doing something else
Final exit
Peter
  • 8,776
  • 6
  • 62
  • 95
  • 4
    Because `exit` does not magically kill the PHP application. – tereško Oct 24 '17 at 14:54
  • 2
    For "The __destruct will not be called" you can see this [stackoverflow link](https://stackoverflow.com/questions/2385047/when-will-destruct-not-be-called-in-php#answer-2385581) – Nebojsa Nebojsa Oct 24 '17 at 14:57
  • [It's even in the manual](https://secure.php.net/manual/en/language.oop5.decon.php): `The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing. ` – txtechhelp Oct 24 '17 at 15:01

0 Answers0