为什么我不能在 __destruct() 方法中设置会话变量?

Why i cant set session var in __destruct() method?

我尝试在 __destruct() 方法中设置会话变量。 方法 __destruct() 是 运行,但未设置会话变量。 同时,__contruct() 或其他方法(例如 test())中的会话按预期工作。

public function test()
{
    $_SESSION['MyVarTest'] = rand(200,300); ← working correctly
}

public function __destruct()
{
    echo 'called';
    $_SESSION['MyVar'] = rand(1,100); ← not working
}

更新版本。现在我尝试原生 PHP Session 和 Symfony 组件,但两者都无法在 __destruct() 方法中工作。

<?php

namespace Project\Modules\Cart\Storage;

use Illuminate\Support\Collection;

class Session
{

    /**
     * @var \Symfony\Component\HttpFoundation\Session\Session
     */
    protected $session;

    protected $cart;

    public function __construct()
    {
        $this->cart  = new Collection();

        $this->session = app('session');
        print_r($_SESSION);

    }

    public function test()
    {
        $this->session->set('json', rand(1,100));  ← working correctly
        $_SESSION['json'] = rand(1,100);  ← working correctly
        return $this->cart->toJson();
    }

    public function __destruct()
    {
        echo 'called';
         $_SESSION['MyVar'] = rand(1,100); ← not working

        $this->session->set('cart', serialize($this->cart->toArray()));  ← not working
    }

}

Symfony 会话正在使用自定义会话处理程序。 (来自 session_set_save_handler

自定义会话处理程序导致 PHP 注册一个关闭函数(即 register_shutdown_function), invoking session_register_shutdown, which adds another shutdown handler (so it will be executed last), calling session_write_close,然后有效地关闭您的会话。

调用该函数后,将不再存储任何写入。 [因为之后将不再调用会话处理程序。]

并且作为析构函数(尚未清理的对象)运行仅在调用关闭函数后,此会话写入将失败。

避免这种情况的唯一解决方案是不使用自定义会话处理程序(我猜这不适合你),手动重新启动会话(只要销毁顺序不首先销毁 class ), 或者在关闭处理程序中或之前显式销毁对该对象的所有引用。