Does anyone knows how to access the value of the public controller variable which has been updated by another function? code example Controller

class MyController extends CI_Controller {

public $variable = array();

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

function index(){
    $this->variable['name'] = "Sam";
    $this->variable['age'] = 19;
}

function another_function(){
    print_r($this->variable);
}

}

when i call another_function() i get an empty array.. What could be the problem? Any help will be apreciated..

有帮助吗?

解决方案

you have to utilize the constructor, instead of index().

    class MyController extends CI_Controller {

    public $variable = array();

    function  __construct() {
        parent::__construct();
        $this->variable['name'] = "Sam";
        $this->variable['age'] = 19;
    }

    function index(){

    }

    function another_function(){
        print_r($this->variable);
    }
    }

If you want to call index(), then call another_function(), try using CI session class.

    class MyController extends CI_Controller {

public $variable = array();

function  __construct() {
    parent::__construct();
    $this->load->library('session');
    if ($this->session->userdata('variable')) {
        $this->variable = $this->session->userdata('variable');
    }
}

function index(){

    $this->variable['name'] = "Sam";
    $this->variable['age'] = 19;
    $this->session->set_userdata('variable', $this->variable);
}

function another_function(){
    print_r($this->variable);
}
        }

其他提示

The index() function is only called when you go to that specific page, i.e index.php/mycontroller/index so going to index.php/mycontroller/another_function won't call the index() function. If you need the user to go to the index page first (in order to get their details) then direct them there first and save the details to a database or in the session variable. If you know the values beforehand (i.e. it's always going to be "Sam" and "19", then put that code in the constructor, which gets called every time you visit a page from that controller.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top