是否可以将以下代码添加到多个函数中而无需单独重新输入代码?
$user_id = $this->tank_auth->get_user_id();
$data['row'] = $this->Profile_model->profile_read($user_id);
我尝试将变量放在构造函数中,但我得到了两个未定义的变量。
答案 0 :(得分:2)
你可以把它变成控制器的私人功能,即
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();
答案 1 :(得分:1)
它只能为您节省一行,但代码行减少了100%!
private function rowData(){
$user_id = $this->tank_auth->get_user_id();
return $this->Profile_model->profile_read($user_id);
}
$data['row'] = $this->rowData();
答案 2 :(得分:0)
好吧,如果你把它放在你需要的构造函数中:
$this->user_id = $this->tank_auth->get_user_id();
$this->data['row'] = $this->Profile_model->profile_read($user_id);
答案 3 :(得分:0)
您可以将此作为控制器的构造函数:
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,并且能够在该控制器的任何函数中使用$ this-> user_id。
答案 4 :(得分:-2)
您是否加载了tank_auth库或将其设置为自动加载?