Symfony 6.1.2购物车开发遇Undefined variable $session错误求助
Symfony 6.1.2购物车功能报错:Undefined variable $session
错误信息
Warning: Undefined variable $session
问题根源
你在Cart.php的get()和remove()方法中直接使用了未定义的$session变量,没有像add()方法那样通过$this->requestStack->getSession()获取会话实例。仅注释了旧的$this->session调用,但未替换为正确的会话获取逻辑。
修正后的Cart.php代码
<?php namespace App\Classe; use Symfony\Component\HttpFoundation\RequestStack; class Cart { private $requestStack; public function __construct(RequestStack $requestStack) { $this->requestStack = $requestStack; } public function add($id) { $session = $this->requestStack->getSession(); $cart = $session->get('cart', []); if (!empty($cart[$id])) { $cart[$id]++; } else { $cart[$id] = 1; } $session->set('cart',$cart); } public function get() { $session = $this->requestStack->getSession(); return $session->get('cart', []); // 添加默认空数组,避免购物车为空时返回null引发后续循环错误 } public function remove() { $session = $this->requestStack->getSession(); return $session->remove('cart'); } }
额外优化提示
get()方法中添加默认值[],确保购物车为空时返回空数组,防止CartController的foreach循环因null报错。- 清理旧的
SessionInterface相关注释,保持代码简洁。
内容的提问来源于stack exchange,提问作者damian
相关产品推荐
相关产品推荐

