3

CI の Auth Tank ライブラリを使用して、特定のユーザーのレコードを照会しています。

この変数$user_id = tank_auth->get_user_id();は、セッションからユーザー ID を取得します。のレコードをプルしたいuser_id = $user_id

私が理解したことから、コンストラクターはクラスが開始されるたびに変数をロードできます。グローバル変数のようなもの。$user_idそこで、モデル クラス内の複数の関数に使用できるように、モデル コンストラクターにmy を設定することにしました。

class My_model extends Model {

    function My_model() 
    {
        parent::Model();
        $user_id = $this->tank_auth->get_user_id();     
    }

        function posts_read() //gets db records for the logged in user
    {       
        $this->db->where('user_id', $user_id);
        $query = $this->db->get('posts');
        return $query->result();
    }
}

次に、モデルをロードし、コントローラーで配列を作成し、foreach ループがあるビューにデータを送信します。

テストするとき、私は得る

メッセージ: 未定義の変数: user_id

私のモデルで。ただし$user_id、関数で変数posts_readを定義すると機能しますが、それを必要とするすべての関数で変数を定義したくありません。

ここで何が間違っていますか?

4

2 に答える 2

11

可変範囲の問題。次のように、他の関数でも使用できるように、クラスレベルの変数を作成する必要があります。

class My_model extends Model {
    private $user_id = null;

    function My_model() 
    {
        parent::Model();
        $this->user_id = $this->tank_auth->get_user_id();     
    }

    // gets db records for the logged in user
    function posts_read()   
    {       
        $this->db->where('user_id', $this->user_id);
        $query = $this->db->get('posts');
        return $query->result();
    }
}

後で:)$user_idで使用されるクラス宣言の後に追加されていることに注意してください。$this->user_id

于 2011-01-09T18:28:27.767 に答える
6

グローバル スコープにプルする

class My_model extends Model {

    $user_id = 0;

    function My_model() {
        parent::Model();
        $this->user_id = $this->tank_auth->get_user_id();     
    }

    function posts_read() //gets db records for the logged in user {       
        $this->db->where('user_id', $this->user_id);
        $query = $this->db->get('posts');
        return $query->result();
    }
}
于 2011-01-09T18:26:49.130 に答える