Search code examples
phpcodeigniterprivate

Declaring private variable in Codeigniter Controller


I'm new to CI and I'm trying to access a private variable through the application, but I set a value to the variable, next time I try to access the function(that I called from a submit form in my view), the private variable that I had set is empty. Can someone help? thx

class Example extends CI_Controller{

    private $_variable;

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        //value from database
        $this->_variable = 'somevalue';
    }

    //calling this function from a view
    public function some_method()
    {
        // code...
        // $this->_variable returning without any value
    }
}

Solution

  • Your views shouldn't directly try to access methods of your controller, instead, you should send those while calling the view in the second arg:

    See Codeigniter's docs related to this (I assume you're spanish, because you use "variable").

    $args = Array( "var1" => "variable", "var2" => "variable" );
    $this->load->view("some_url", $args);
    

    Then $var1 and $var2 will be available in your view.