开发者

Codeigniter reusable $data in controller functions

开发者 https://www.devze.com 2023-03-17 12:31 出处:网络
I\'m quite new to CodeIgniter and I\'m trying to re-use the $data I pass to a view in another function from the same controller.

I'm quite new to CodeIgniter and I'm trying to re-use the $data I pass to a view in another function from the same controller.

I have the following code :

class MyClass extends CI_Controller
{
    function func1()
    {
        $this->mdata['first'] = "first";
        $t开发者_如何学运维his->mdata['second'] = "second";  
        $this->load->view('my_view', $this->mdata);
    }

    function func2()
    {
        var_dump($this->mdata);
    }
}

The fact is that apparently, I can't use my variable in the func2()...

Does someone has a trick to do so ?

Thanks.

B


Create a private method _create_mdata() and call it in both methods. There is no way to literally share the data without doing something like this.

// methods starting with an underscore are considered private by CodeIgniter.
// you may want to actually declare it private though. That is better practice
function _create_mdata() 
{
    $this->mdata['first'] = "first";
    $this->mdata['second'] = "second";  
}

function func1()
{
    $this->_create_mdata(); 
    // continue with func1
}


class Your_Class {
    public $mdata;

    function func1()
    {
        $this->mdata['first'] = "first";
        $this->mdata['second'] = "second";  
        $this->load->view('my_view', $this->mdata);
    }

    function func2()
    {
        var_dump($this->mdata);
    }
}

Now "$this->mdata" will work.

Hope it helps.


func1 is only called when the user browser to yoursite.com/myclass/func1. Now, going to func2 using the url only calls func2. Therefore, the mdata values are not assigned. You could use a constructor where you assign those values. I'll put up a code example when I have more time.


Pseudo code i haven't tested. And you probably should autoload session.

   class Your_Class {

        function func1()
        {
            $this->load->library('session');

            $mdata = array( 'mdata' => array(   'first' => 'first',
                                                'second' => 'second'
                                            )
                         )  
            $this->session->set_userdata($mdata);

            $this->load->view('my_view', $mdata['mdata']);
        }

        function func2()
        {
            $this->load->library('session');
            $mdata = $this->session->userdata('mdata');
            var_dump($mdata);
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消