是否有可能在__construct完成之前调用__destruct?

时间:2017-02-15 13:29:34

标签: php constructor destructor

我有一个项目leash,在JSON-RPC服务中我写了__destruct中的文件,但有时配置文件被清除(看起来像这个{"sessions":[],"users":[]})它发生了有时候,当我在ajax请求完成之前快速刷新页面时,看起来__constructor在调用__destruct之前没有完成,我的代码如下:

class Service {
    protected $config_file;
    protected $config;
    const password_hash = 'h'; // function use for password on installation
    const password_regex = '/([A-Za-z_][A-Za-z0-9_]*):(.*)/';

    function __construct($config_file, $path) {
        $this->path = $path;
        $this->config_file = $config_file;
        $full_path = $path . "/" . $this->config_file;
        if (file_exists($full_path)) {
            try {
                $this->config = json_decode(file_get_contents($full_path));
            } catch (Exception $e) {
                $this->config = new stdClass();
            }
            // it had no write permission when first created while testing
            if (!is_writable($full_path)) {
                chmod($full_path, 0664);
            }
        } else {
            $this->config = new stdClass();
        }
        if (!isset($this->config->sessions) || !is_array($this->config->sessions)) {
            $this->config->sessions = array();
        } else {
            $this->config->sessions = array_map(function($session) {
                return Session::cast($session);
            }, array_filter($this->config->sessions, function($session){
                return isset($session->token) && isset($session->username);
            }));
        }
        if (!isset($this->config->users) || !is_array($this->config->sessions)) {
            $this->config->users = array();
        }
    }
    // ------------------------------------------------------------------------
    function __destruct() {
        $path = $this->path . "/" . $this->config_file;
        $this->__write($path, json_encode($this->config));
    }

我还有其他修改配置对象的方法,如login,可以将新会话添加到$this->config->sessions数组。 Here is full file

我已经尝试添加标记$this->corrupted,当我获得例外时它设置为true但它没有解决问题,它必须是时间问题被叫__destruct

我还尝试添加在构造函数的最后一行中设置为true的标志$this->safe_to_save,但这也没有用。可能是什么问题?

0 个答案:

没有答案