[英]Create constructor method in controller in Yii
I have just started to learn Yii
, where I have created one PostController
Controller. 我刚开始学习
Yii
,我在那里创建了一个PostController
控制器。 In this controller I am having one requirement of using Sessions
. 在这个控制器中,我有一个使用
Sessions
要求。
So I have created one constructor method and its code is as follows 所以我创建了一个构造函数方法,其代码如下
public $session;
public function __construct() {
$this->session = new CHttpSession;
$this->session->open();
}
But after creating this constructor the controller was not working and gives error. 但在创建此构造函数后,控制器无法正常工作并出错。 And after deleting this code my controller was working perfectly.
删除此代码后,我的控制器工作正常。 I have written this code inside constructor to not initialize the
Session
in each method for actionCreate
and actionUpdate
. 我在构造函数中编写了这段代码,以便在
actionCreate
和actionUpdate
每个方法中初始化Session
。
So my question is how can we create constructor in Yii
? 所以我的问题是如何在
Yii
创建构造函数?
Thanks 谢谢
You simply forgot to call parent constructor : 你只是忘了调用父构造函数:
public function __construct()
{
.....
parent::__construct();
}
You could use beforeAction
instead of overriding __construct
. 您可以使用
beforeAction
而不是覆盖__construct
。
And Sergey is right, by default Yii will start session ( autoStart
), you just have to use Yii::app()->session
, eg : 谢尔盖是对的,默认情况下Yii会启动会话(
autoStart
),你只需要使用Yii::app()->session
,例如:
Yii::app()->session['var'] = 'value';
public function __construct()
{
parent::__construct($this->id, $this->module);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.