CodeIgniter Forums
Sessions not being set when setting from library - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Sessions not being set when setting from library (/showthread.php?tid=56965)



Sessions not being set when setting from library - El Forum - 02-03-2013

[eluser]Unknown[/eluser]
I am about to pull my hair out over this, so someone please help!

The simplest case of this is as follows:

Controller:

Code:
<?php

class Test_Controller extends CI_Controller
{
    public function test_a()
    {
        $this->load->library('test_lib');
        $this->test_lib->test();
    }

    public function test_b()
    {
        var_dump($this->session->userdata('test'));
    }
}

Library:

Code:
<?php

class Test_lib
{
    protected $_ci;

    public function __construct()
    {
        $this->_ci=get_instance();
    }

    public function test_a()
    {
        $this->_ci->session->set_userdata('test',array('testdata'));
    }
}

Send a request to test_controller/test_a, then to test_b. You'll see that the data that is dumped is false, instead of the expected test data.


Sessions not being set when setting from library - El Forum - 02-03-2013

[eluser]Sanjay Sarvaiya[/eluser]
Hi,
You are calling test() method on library which one is not exist I think it should be test_a();

Code:
$this->test_lib->test_a();
instead of  $this->test_lib->test();
for session you must have to load session library on construct of test_lib
Code:
$this->_ci->load->library('session');



Sessions not being set when setting from library - El Forum - 02-04-2013

[eluser]PhilTem[/eluser]
Code:
public function __construct()
    {
        $this->_ci =& get_instance(); // Assign by reference, don't make a copy of the object
    }

That's probably your problem Wink