我尝试在 __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
}
}