无法在其他控制器中获取会话数据

I'm using symfony 3.4. I'm able to set and get session data within the same controller. But getting the same session data in other controllers throwing an exception : "Call to a member function get() on null".

Below is the code i'm using :

   Controller1.php(Working)
   $this->session = new Session();
   $this->session->start();    
   /*** Set Session Data ***/
   $this->session->set('userid', $dbres [0]['user_id']);

   /*** Get Session Data ***/
   $user_id = $this->session->get('userid');

   Controller2.php(Not Working) 
   /*** Get Session Data ***/
   $user_id = $this->session->get('userid');

   Exception : "Call to a member function get() on null"

Controller1.php(Working)

 $this->session = new Session();
   $this->session->start();    
   /*** Set Session Data ***/
   $this->session->set('userid', $dbres [0]['user_id']);

   /*** Get Session Data ***/
   $user_id = $this->session->get('userid');

Controller2.php(Not Working)

  /*** Get Session Data ***/
   $this->session = new Session();
   $this->session->start();    
   $user_id = $this->session->get('userid');

Exception : "Call to a member function get() on null" Because you have not define $this->session on controller 2

Why don't you passed SessionInterface in your action? Like this:

public function showAction(SessionInterface $session)
{
    $session->set('user_id', 1);
}

so in your Controller 2 you can get user_id like this:

public function showAction(SessionInterface $session)
{
    $session->get('user_id'); // You can test $session->has('user_id')
}

If you want create a particular session create an User (or other) class with a static method getInstance and private constructor. In the create method test if session exist if true return session else call the constructor. Here an example:

public static function getInstance($new = false)
{
    if(is_null(self::$_session)) {
        self::$_session = new Session();
        self::$_session->start();
    }

    if($new)
    {
        self::$_session->set('user_instance', new self(self::$_session));
        return self::$_session->get('user_instance');
    }

    if(!self::$_session->has('user_instance')) {
        self::$_session->set('user_instance', new self(self::$_session));
    }

    return self::$_session->get('user_instance');
}

I hope that it will help you.