8

別の関数によって更新されたパブリックコントローラー変数の値にアクセスする方法を知っている人はいますか? コード例 コントローラー

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);
}

}

another_function() を呼び出すと、空の配列が返されます..何が問題なのですか? どんな助けも高く評価されます..

4

2 に答える 2

11

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);
    }
    }

を呼び出してから を呼び出したい場合はindex()another_function()CIセッションクラスを使用してみてください。

    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);
}
        }
于 2011-06-16T20:09:24.783 に答える
2

このindex()関数は、その特定のページに移動したときにのみ呼び出されます。つまりindex.php/mycontroller/index、going toは関数index.php/mycontroller/another_functionを呼び出しませんindex()。(詳細を取得するために) ユーザーが最初にインデックス ページに移動する必要がある場合は、まずそこに誘導し、詳細をデータベースまたはセッション変数に保存します。事前に値がわかっている場合 (つまり、常に "Sam" と "19" になる場合)、そのコードをコンストラクターに入れます。コンストラクターは、そのコントローラーからページにアクセスするたびに呼び出されます。

于 2011-06-16T12:46:26.817 に答える