コードを個別に再入力することなく、複数の関数に次のコードを追加することはできますか?Codeigniterが複数のコントローラ関数に変数を渡す
$user_id = $this->tank_auth->get_user_id();
$data['row'] = $this->Profile_model->profile_read($user_id);
私は変数をコンストラクタに入れようとしましたが、両方に対して未定義の変数があります。
コードを個別に再入力することなく、複数の関数に次のコードを追加することはできますか?Codeigniterが複数のコントローラ関数に変数を渡す
$user_id = $this->tank_auth->get_user_id();
$data['row'] = $this->Profile_model->profile_read($user_id);
私は変数をコンストラクタに入れようとしましたが、両方に対して未定義の変数があります。
あなたのコントローラで、コントローラのプライベート関数へのすべての機能、すなわち
private function get_user_id()
{
$user_id = $this->tank_auth->get_user_id();
return $this->Profile_model->profile_read($user_id);
}
そしてそれを回すことができるが行います
$data['row'] = $this->get_user_id();
をさてあなたは、コンストラクタでそれを置く場合
$this->user_id = $this->tank_auth->get_user_id();
$this->data['row'] = $this->Profile_model->profile_read($user_id);
私は試みましたが、両方とも空のプロパティにアクセスできない – CyberJunkie
tank_authライブラリを読み込んだり、自動ロードするよう設定しましたか?
1行しか保存しませんが、コード行は100%減少します。
class Example extends CI_Controller {
protected $user_id;
function __construct()
{
parent::__construct();
$this->load->library('tank_auth');
$this->load->model('Profile_model');
$this->user_id = $this->tank_auth->get_user_id();
$data['row'] = $this->Profile_model->profile_read($this->user_id);
$this->load->vars($data);
}
}
をし、そのコンストラクタからロードされ、後続のビューで$行へのアクセス権を持っている、などの$ this - を使用することができます:あなたは、コントローラのコンストラクタとしてこれを持つことができます
private function rowData(){
$user_id = $this->tank_auth->get_user_id();
return $this->Profile_model->profile_read($user_id);
}
$data['row'] = $this->rowData();
> user_idを使用してください。
ありがとう、私はコンストラクタにコードを入れようとしましたが、コントローラの関数でそれを使用しようとするとどこでも '$ user_id'の変数は未定義です。 – CyberJunkie
この例の変更を確認し、使用するコントローラ関数の中で$ this-> user_idを使用してから、ビューのいずれかで$ rowを使用します。それはあなたがやろうとしていることですか? – tgriesser
thx、それも試して、 '空のプロパティにアクセスできない – CyberJunkie
ありがとうございます!私はなぜあなたが 'private'ではなく' protected'を使っているのだろうと思っていますか? – CyberJunkie
ハハ - 私はプライベートを意味する申し訳ありません! :)睡眠が必要です –
Heh問題はありません:)私はちょうど '保護'が大きな利点を提供するかどうか考えていた。 – CyberJunkie