[英]Codeigniter pass variables to to multiple controller functions
是否可以在不單獨重新鍵入代碼的情況下將以下代碼添加到多個函數中?
$user_id = $this->tank_auth->get_user_id();
$data['row'] = $this->Profile_model->profile_read($user_id);
我嘗試將變量放在構造函數中,但我得到了兩個未定義的變量。
你可以把它交給 controller 的私有 function,即
private function get_user_id()
{
$user_id = $this->tank_auth->get_user_id();
return $this->Profile_model->profile_read($user_id);
}
然后在您的 controller 中的每個 function 中執行:
$data['row'] = $this->get_user_id();
它只為您節省了一行代碼,但代碼行數減少了 100%!
private function rowData(){
$user_id = $this->tank_auth->get_user_id();
return $this->Profile_model->profile_read($user_id);
}
$data['row'] = $this->rowData();
好吧,如果你把它放在你需要的構造函數中:
$this->user_id = $this->tank_auth->get_user_id();
$this->data['row'] = $this->Profile_model->profile_read($user_id);
您可以將其作為控制器的構造函數:
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);
}
}
並且您將可以在從該構造函數加載的任何后續視圖中訪問 $row,並且能夠在該 controller 的任何函數中使用 $this->user_id。
資料來源: http://codeigniter.com/user_guide/libraries/loader.html
您是否加載了 tank_auth 庫或將其設置為自動加載?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.