Does PHP destructors get called all the time when script execution ends?

Well I am developing a library in which I want to prevent accessing superglobal arrays. One issue I have is $_SESSION, since if you remove a session var from the superglobal array, it will not be available when the user goes to another page or refresh the page. However, I have come out with an interesting solution, the destructor. Below is a part of the code from my HTTP Session class that should demonstrate how it works:

namespace Mysidia\Resource\HTTP;
use Mysidia\Resource\Lang\Object;
use Mysidia\Resource\Lang\Dictionary;

final class Session extends Object{

    private $params;

    public function __construct(){
        $this->params = new Dictionary;
        foreach($_SESSION as $key => $value){
            $this->params[$key] = $value;
            unset($_SESSION[$key]);
        }
    }

    // methods to retrieve, add, update or remove session variables omitted for simplicity

    public function __destruct(){
        foreach($this->params as $key => $value){
            $_SESSION[$key] = $value;
        }
    } 
}

This way, the contents inside superglobal $_SESSION are destroyed when my HTTP Session class is created, and recreated when the HTTP Session class is destroyed/garbage collected(so the session vars will persist until session expires). It will effectively prevent client users to access $_SESSION directly, and they will need to use the HTTP Session class instead. One reason for this is that it can prevent isset checks all over the place. Another reason is that the class can provide additional methods/API to retrieve serialized objects/arrays. And of course, superglobals are bad.

However, this will only work under the assumption that class destructor will be called each time the script execution ends. I am not sure about this, which is why I am asking. Consider the three scenarios: 1. Script terminated normally, no error or exception; 2. Script terminated normally, with caught exceptions; 3. Script terminated abnormally, with uncaught exceptions or fatal errors. Will destructors of my HTTP Session be called in each of these scenarios? Or it will only be called if there are no error or exceptions? Anyone know about this?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.