Php 在Symfony中更改当前用户的用户对象会将我注销

Php 在Symfony中更改当前用户的用户对象会将我注销,php,symfony,Php,Symfony,我有以下代码: public function editAction(Request $request) { $user = $this->get('security.context')->getToken()->getUser(); // Get the user $user2 = $this->getDoctrine() ->getRepository('OpinionsUserBundle:User')

我有以下代码:

public function editAction(Request $request)
{
    $user = $this->get('security.context')->getToken()->getUser();

    // Get the user
    $user2 = $this->getDoctrine()
        ->getRepository('OpinionsUserBundle:User')
        ->findOneById($user->id);

    echo $user->email . '<br>'; // Echo me@example.org
    echo $user2->email . '<br>'; // Echo me@example.org

    $user2->email = 'blah';

    echo $user->email; // Echoes blah
    die();
}
公共函数编辑操作(请求$Request)
{
$user=$this->get('security.context')->getToken()->getUser();
//获取用户
$user2=$this->getDoctrine()
->getRepository('OpinionSumberBundle:User')
->findOneById($user->id);
echo$user->email.“
”;//echome@example.org echo$user2->email.“
”;//echome@example.org $user2->email='blah'; echo$user->email;//回显废话 模具(); }
所以我知道,条令一定是在引用。问题是我有一个表单,用户可以更改他们的姓名和电子邮件,但如果电子邮件已经在使用中,我想显示一个错误。但是,当我检查验证时,Symfony会将数据绑定到用户对象,因此会话会以某种方式使用新的用户对象进行更新,将我注销或更改我的用户


如何避免这种情况?

如果表单验证失败,我最终使用的解决方案是刷新用户模型(将其恢复为原始状态)

// Reset to default values or else it will get saved to the session
$em = $this->getDoctrine()->getManager();
$em->refresh($user);

您的示例证明,这些不是对同一对象的引用(您已将电子邮件更改为$user2,$user的电子邮件保持不变)。下面是一个很好的例子。祝你一切顺利!