是否可以将以下代码添加到多个函数中,而无需单独重新输入代码?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库还是将它设置为autoload?
它只会为您节省一行,但代码行数量会减少100%!
private function rowData(){
$user_id = $this->tank_auth->get_user_id();
return $this->Profile_model->profile_read($user_id);
}
$data['row'] = $this->rowData();
您可以将此作为控制器的构造函数:
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);
}
}
,你将有机会获得$行从构造函数加载的任何后续视图,以及能够使用$这 - > user_id在该控制器的任何功能中。
谢谢,我曾尝试把代码放在构造函数中,但是我在'$ user_id'中获取未定义的变量,无论我尝试在控制器函数中使用它。 – CyberJunkie
检查对示例的更改,在您希望使用它的任何控制器函数中使用$ this-> user_id,然后在任意视图中使用$ row。那是你想要做的吗? – tgriesser
thx,也试过,并得到'不能访问空的属性' – CyberJunkie
谢谢!我只是想知道为什么你使用'protected'而不是'private'? – CyberJunkie
哈 - 对不起,我的意思是私人的!需要睡眠:) –
heh没问题:)我只是在想如果'protected'提供了更大的优势。 – CyberJunkie