Codeigniter 构造函数 - 加载数据库 +设置变量
我想知道如何将以下代码添加到我的 codeigniter 构造函数中:
$this->load->model('members_model');
$member = $this->session->userdata('email_address');
$viewdata['pagecontent'] = $this->members_model->get_profile($member);
该代码在我的整个控制器中使用,每次都重复它似乎很愚蠢。当我尝试将其添加到构造函数时,我无法引用设置的变量。
这是到目前为止的构造函数:
public function __construct(){
parent::__construct();
Accesscontrol_helper::is_logged_in_super_user();
$this->load->model('members_model');
$member = $this->session->userdata('email_address');
$viewdata['pagecontent'] = $this->members_model->get_profile($member);
}
为什么上面的代码不起作用?构造函数需要不同的代码吗?
I would like to know how I can add the following code to my codeigniter constructor:
$this->load->model('members_model');
$member = $this->session->userdata('email_address');
$viewdata['pagecontent'] = $this->members_model->get_profile($member);
The code is used throughout my controller and it seems silly to repeat it every time. When I try adding it to the constructor I am unable to reference the set variables.
This is the constructor so far:
public function __construct(){
parent::__construct();
Accesscontrol_helper::is_logged_in_super_user();
$this->load->model('members_model');
$member = $this->session->userdata('email_address');
$viewdata['pagecontent'] = $this->members_model->get_profile($member);
}
Why wouldn't the above code work? Do constructors require different code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从这个意义上说,构造函数的工作方式与所有其他方法(以及类似函数)一样,因此您的变量受变量范围的约束。
执行:
然后,在其他控制器的方法中,只需调用类属性 $this->viewdata,例如。
并在 myview.php 中访问它:
Constructor works, in this sense, like all other methods (and like functions), so your vars are subject to the variable scope.
Do:
Then, in your other controller's methods, you just call the class property $this->viewdata, ex.
And access it, in myview.php :
您似乎遇到了一些范围问题。由于变量是在 __construct() 方法内部声明的,因此这是唯一能够引用它们的方法。您需要将它们设为类变量,以便在所有方法中访问它们。
尝试这样的方法:
然后您可以在其他方法中引用
$member
和$viewdata
,如下所示:$this->member
您可以想要稍微不同地设置它,但希望您了解变量和范围。
It looks like you are having some scope issues. Since the variables are declared inside of the
__construct()
method, that is the only method that is able to reference them. You would need to make them class variables in order to have access to them in all of your methods.Try something like this:
Then you can reference
$member
and$viewdata
in your other methods like this:$this->member
You may want to set this up a little differently, but hopefully you get the idea about variables and scope.